<?php





namespace app\shop\model;



use app\crm\model\FollowRecord;

use app\admin\model\Common;

use app\shop\model\AddOrderLog;
use Kingdee\Kingdee;

use think\facade\Db;

use think\model\concern\SoftDelete;

use app\common\traits\ActionRecordTrait;

use app\shop\model\RefundPayModel;


use app\shop\model\TurnRefund;


/**

 * 订单模型

 * @package app\shop\model

 * @author LIU

 * @create 2021-10-01

 */

class Refund extends Common

{

    use ActionRecordTrait;



    /**

     * 表名

     * @var string

     */

    protected $name = 'shop_refund_order';

    protected $defaultSoftDelete = 0;



    /**

     * 获取sku信息

     * @return \think\model\relation\hasOne

     * @author SL

     * @create 2021-05-27 15:04

     */

    public function orderGoods()

    {

        return $this->hasOne(Goods::class,'id');

    }





    /**

     * 获取订单列表

     * @param  array $request 请求参数

     * @return array

     * @author LIU

     * @create 2021-10-26

     */

    public function getModeList($request)

    {

        try {

            try {

                $refund_mode = $request['refundMode'] ?? '';

                $where = [];

                array_push($where,['status','=',1]);

                if($refund_mode == '1' || $refund_mode == '3' ){

                    array_push($where,['refund_mode','in',['02','03']]);

                }

                $list = Db::name('refund_mode')->where($where)->select();

                $data              = [];

                $data['list']      = $list ?? [];

                return $data;

            }catch (\Exception $e) {

                $this->error = $e->getMessage();

                return [];

            }



        }catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];

        }

    }











    /**

     * 获取订单列表

     * @param  array $request 请求参数

     * @return array

     * @author LIU

     * @create 2021-10-26

     */

    public function getDataList($request)

    {
        


        try {

            $userId  = $request['user_id'] ?? 0;

            $shopIds= $request['shopIds'] ?? '';

            $person_shop_id = isset($request['person_shop_id'])?$request['person_shop_id']:0; //当前登陆人所属门店id
            $admin_user_id = isset($request['admin_user_id'])?$request['admin_user_id']:0;//当前登陆人id

            $request = $this->fmtRequest($request);

            $is_show_add = true;

            if(!empty($person_shop_id)){
                $position_id = DB::name('shop_person')->where('id',$admin_user_id)->value('position_id');
                $is_show_add = in_array($position_id,[7,10]) ? true:false;
            }




            $map     = $request['map'] ?? [];

            $where   = [];

            if (!isset($map['type']))

            {

                $this->error = '请传入type类型';

                return [];

            }

            if (!in_array($map['type'],[1,2,3]))

            {

                $this->error = 'type类型不正确';

                return [];

            }



            $id = isset($map['id']) && $map['id'] ? $map['id'] : [];

            if ($id) {

                if (!is_array($id)) {

                    $id = [$id];

                }

                array_push($where, ['o.id', 'in', $id]);

            }

            // array_push($where, ['o.status', '<>', 3]);//排除已作废的

            $type      =$map['type']; // 订单类型 1退款单 2退货单 3收款单

            $uid      = isset($map['uid']) && $map['uid'] ? trim($map['uid']) : ''; // 会员id

            $shop_id      = isset($map['shop_id']) && $map['shop_id'] ? trim($map['shop_id']) : ''; // 门店id

            //$refund_order_no     = isset($map['refund_order_no']) && $map['refund_order_no'] ? trim($map['refund_order_no']) : ''; // 单号

            $consignee = isset($map['consignee']) && $map['consignee'] ? trim($map['consignee']) : ''; // 客户名称

            $status       = isset($map['status']) && intval($map['status']) ? intval($map['status']) : 0; // 订单状态

            $start_time = isset($map['start_time']) && $map['start_time'] ? strtotime(date($map['start_time'])) : 0;

            $end_time = isset($map['end_time']) && $map['end_time'] ? strtotime(date($map['end_time'] . ' 23:59:59')) : 0;

            $shop_name = isset($map['shop_name']) && $map['shop_name'] ? trim($map['shop_name']) : ''; // 门店名称

            $business_type    = isset($map['business_type']) && intval($map['business_type']) ? intval($map['business_type']) : 0; // 订单状态

            $order_type       = isset($map['order_type']) && intval($map['order_type']) ? intval($map['order_type']) : 0; // 订单状态

            $low_total = isset($map['low_total']) && $map['low_total'] ? $map['low_total']: 0;//销售金额区间搜索最小值

            $large_total =  isset($map['large_total']) && $map['large_total'] ? $map['large_total']: 0;//销售金额区间搜索最大值

            $is_pay = $map['is_pay'] ?? ''; // 订单是否支付

            $display_cannel = isset($map['display_cannel']) && intval($map['display_cannel']) ? intval($map['display_cannel']) : 0; // 订单状态

            // echo "<pre>";
            // print_r($map);
            // echo "</pre>";

            // echo "是否支付：".$is_pay;
            // exit;

            // 获取客户数据权限 的客户名称

            if ($shopIds)

            {

                array_push($where, ['o.shop_id', 'in', $shopIds]);

            }

            if ($uid)

            {

                //门店id搜索

                array_push($where, ['o.uid', '=', $uid]);

            }

            if ($type)

            {

                //门店名称搜索

                array_push($where, ['o.type', '=', $type]);

            }

            if ($shop_id)

            {

                //门店名称搜索

                array_push($where, ['o.shop_id', '=', $shop_id]);

            }

            if ($consignee) {

                // 客户名称搜索

                array_push($where, ['o.consignee', 'like', '%'.$consignee.'%']);

            }



            if ($shop_name)

            {

                //门店名称搜索

                array_push($where, ['o.shop_name', 'like', '%'.$shop_name.'%']);

            }

            if ($consignee) {

                // 客户搜索

                array_push($where, ['o.consignee', 'like', '%'.$consignee.'%']);

            }

            if ($status != -1) {

                array_push($where, ['o.status', '=', $status]);

            }

            if ($is_pay == '0') {

                array_push($where, ['o.is_pay', '=', $is_pay]);

            }

            // if ($refund_order_no) {

            // array_push($where, ['o.refund_order_no', '=', $refund_order_no]);



            // }



            // 时间

            if($start_time && $end_time)

            {

                array_push($where, ['o.deal_time', 'between', "$start_time,$end_time"]);

            }



            if ($business_type)

            {

                //业务类型搜索

                array_push($where, ['o.business_type', '=', $business_type]);

            }

            if ($order_type)

            {

                //订单类型搜索

                array_push($where, ['o.order_type', '=', $order_type]);

            }

            //退货单以订单总额搜索

            if ($type==2)

            {

                if ($low_total && !$large_total)

                {

                    array_push($where, ['o.total_amount', 'egt', $low_total]);

                }

                if (!$low_total && $large_total)

                {

                    array_push($where, ['o.total_amount', 'elt', $large_total]);

                }

                if ($low_total && $large_total)

                {

                    array_push($where, ['o.total_amount', 'between', "$low_total,$large_total"]);

                }

            }else

            {

                //收款单 退款单以实际金额搜索

                if ($low_total && !$large_total)

                {

                    array_push($where, ['o.pay_amount', 'egt', $low_total]);

                }

                if (!$low_total && $large_total)

                {

                    array_push($where, ['o.pay_amount', 'elt', $large_total]);

                }

                if ($low_total && $large_total)

                {

                    array_push($where, ['o.pay_amount', 'between', "$low_total,$large_total"]);

                }

            }



            $sqlQuery = $this->alias('o')

                ->where($where);

            // $dataCount  = $sqlQuery->count();


            if($display_cannel == 0)
            {
                array_push($where,['o.status','<>',3]);

            }

            if (in_array($type,[1,3]))
            {
                
                $field = ['o.id','o.consignee', 'o.order_type','o.is_lock','business_type','o.shop_name','o.create_time','o.shop_id','o.deal_time','o.type','o.type','o.sale_name','c.king_no','g.refund_mode_name','g.pay_price','g.gift_price','g.shop_transfer_price','o.refund_type','o.refund_type_plus','o.is_pay','o.is_pay_time','o.status','o.extra_type'];
                $dataCount = $this->alias('o')->field($field)->where($where)
                    ->join('customer c', 'o.uid = c.id')
                    ->join('shop_refund_order_goods g', 'o.id = g.order_id')
                    ->count();
                   
            }else{
                $field = ['o.id','o.goods_price','o.consignee', 'o.is_lock','o.total_amount','o.shop_name','o.order_type','o.business_type','o.create_time','o.shop_id','o.sale_name','o.deal_time','o.type','c.king_no','o.refund_type','o.refund_type_plus','o.is_pay','o.is_pay_time','o.status','o.extra_type'];
                $dataCount = $this->alias('o')->field($field)->where($where)
                    ->join('customer c', 'o.uid = c.id')
                   ->count();
            }

            $sum_ben_amount=0;

            $sum_zeng_amount=0;

            $sum_amount  =0;

            if ($dataCount) {

                // 订单列表

                if($display_cannel == 0)
                {
                    $sqlQuery = $sqlQuery->where('o.status','<>',3);
                }

                //退款单 收款单

                if (in_array($type,[1,3]))

                {
                    
                    $sum_ben_amount  = $this->alias('o')

                        ->where($where)->where('o.status','<>',3)->sum('o.pay_amount');

                    $sum_zeng_amount  = $this->alias('o')

                        ->where($where)->where('o.status','<>',3)->sum('o.gift_amount');

                    // $sum_ben_amount  = $sqlQuery->sum('o.pay_amount');

                    // $sum_zeng_amount  = $sqlQuery->sum('o.gift_amount');

                    $field = ['o.id','o.consignee', 'o.order_type','o.is_lock','g.data_business_type as business_type','g.data_business_two_type as business_two_type','o.shop_name','o.create_time','o.shop_id','o.deal_time','o.type','o.type','o.sale_name','c.king_no','g.refund_mode_name','g.pay_price','g.gift_price','g.shop_transfer_price','o.refund_type','o.refund_type_plus','o.is_pay','o.is_pay_time','o.status','o.extra_type'];


                    $list = $sqlQuery->field($field)

                        ->join('customer c', 'o.uid = c.id')

                        ->join('shop_refund_order_goods g', 'o.id = g.order_id')

                        ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])

                        ->order('id DESC')

                        ->select()->toArray();

                }else{

                    // $sum_amount  =$sqlQuery->sum('o.total_amount');

                    $sum_amount  = $this->alias('o')

                        ->where($where)->where('o.status','<>',3)->sum('o.total_amount');

                    //退货单

                    $field = ['o.id','o.goods_price','o.consignee', 'o.is_lock','o.total_amount','o.shop_name','o.order_type','o.business_type','o.business_two_type','o.create_time','o.shop_id','o.sale_name','o.deal_time','o.type','c.king_no','o.refund_type','o.refund_type_plus','o.is_pay','o.is_pay_time','o.status','o.extra_type'];


                    $list = $sqlQuery->field($field)

                        ->join('customer c', 'o.uid = c.id')

                        ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])

                        ->order('id DESC')

                        ->select()->toArray();

                }


//                var_dump($list);die;


                if ($list) {

                    $businessType = Db::name('customer_balance_category')->column('name','id');
                    $businessTwoType = [1=>'身体项目',2=>'皮肤项目'];
                    foreach($list as &$v){

                        if (in_array($type,[1,3])){
                            $v['price_sum'] = bcadd(bcadd($v['pay_price'],$v['gift_price'],2),$v['shop_transfer_price'],2);
                        }
                        $v['order_type']=$v['order_type']==1?'新单':'补单';

                        $v['business_type'] = $businessType[$v['business_type']]??'暂无数据';
                        $v['business_two_type'] = $businessTwoType[$v['business_two_type']]??'暂无数据';

                        // $v['refund_type'] = $v['refund_type'] ?? '';

                        $refund_type = '';
                        if($v['refund_type']=='101.01'){
                            $refund_type = '店面转诊';
                        }elseif ($v['refund_type']=='101.02') {
                            if($v['type']=='1'){
                                $refund_type = '退款';
                            }else if($v['type']=='3'){
                                $refund_type = '收款';
                            }

                        }else {

                            if($v['type']=='1'){
                                $refund_type = '退款调整';
                            }else if($v['type']=='3'){
                                $refund_type = '收款调整';
                            }
                        }

                        $v['refund_type']=$refund_type;

                        $v['deal_time']=date('Y-m-d', $v['deal_time']);

                        if($v['is_pay']=='0'){

                            $v['is_pay']='未支付';

                            $v['is_pay_time']='';

                        }elseif($v['is_pay']=='1'){

                            if($v['refund_type_plus']=='2'){

                                $v['is_pay']='已支付';

                                $v['is_pay_time']='-';

                            }else{

                                $v['is_pay']='已支付';

                                $v['is_pay_time']=date('Y-m-d H:i:s', $v['is_pay_time']);

                            }


                        }else {
                            $v['is_pay']='-';

                            $v['is_pay_time']='-';
                        }

                        if($v['refund_type_plus']=='1'){
                            $v['refund_type_plus']='扫码支付';
                        }elseif($v['refund_type_plus']=='2'){
                            $v['refund_type_plus']='传统支付';
                        }elseif($v['refund_type_plus']=='3'){
                            $v['refund_type_plus']='线上支付';
                        }else {
                            $v['refund_type_plus']='-';
                        }

                        switch ($v['status']) {
                            case '1':
                                $v['status_msg'] = '已退款';
                                break;
                            case '2':
                                $v['status_msg'] = '已下推';
                                break;
                            case '3':
                                $v['status_msg'] = '已作废';
                                break;
                            default:
                                $v['status_msg'] = '未完成';
                                break;
                        }
                        if($v['extra_type']==1&&$v['business_type']=="疤痕")
                        {
                            $v['extra_type']="青春痘";
                        }else{
                            $v['extra_type']="";
                        }

                    }

                }

            }




            $permission = get_user_permission_menu($userId,'order_list_tag');



            $data              = [];

            $data['menu_list'] = $permission ? $permission : [];

            $data['list']      = $list ?? [];

            $data['dataCount'] = $dataCount ?? 0;

            $data['is_show_add'] = $is_show_add;





            if($start_time && $end_time) {

                if (in_array($type, [1, 3])) {

                    $data['sum_ben_amount'] = $sum_ben_amount ?? 0;

                    $data['sum_zeng_amount'] = $sum_zeng_amount ?? 0;

                } else {

                    $data['sum_amount'] = $sum_amount ?? 0;

                }

            }


            return $data;

        } catch (\Exception $e) {
         

            $this->error = $e->getMessage();

            return [];

        }

    }



    /**

     * 订单主要详情

     * @param array $request

     * @return array

     * @author SL

     * @create 2021-06-02

     */

    public function getDataDetail($request)

    {

        try {

            $id = $request['order_id'] ?? 0;

            if(!$id){

                $this->error = '请传入订单id';

                return [];

            }

            $type = $request['type'] ?? 0;

            if(!$type){

                $this->error = '请传入退款单类型';

                return [];

            }

            $detail = [];

            if (in_array($type,[1,3]))

            {

                $field = ['id,type,consignee,refund_order_no,operator_name,shop_name,business_type,order_type,status,total_amount,pay_amount,gift_amount,shop_transfer_amount,is_treatment,referral_shop_name,
                
                            deal_time,create_time,king_push_time,king_status,description,sales_policy,refund_type,is_pay,refund_type_plus,shop_id,order_class,refunder,refund_account,business_two_type', 'is_experience,is_outreach,outreahc_name,is_introduction,introduction_name', 'sales_name','settlement_name','market_name','king_num','combo',
                    'experience_id,outreahc_id,introduction_id,experience_name,extra_type,sale_id,sale_name,refund_type_plus,shanghu_type,project_type' ];

            }else
            {

                $field = ['id,type,refund_order_no,consignee,operator_name,shop_name,business_type,income_type,order_type,status,total_amount,gift_amount,shop_transfer_amount,refund_type_plus,shanghu_type,

            pay_amount,deal_time,create_time,king_push_time,king_status,sales_policy,shop_id,order_class,refunder,refund_account,business_two_type', 'is_experience,is_outreach,outreahc_name,is_introduction,introduction_name', 'sales_name','settlement_name','market_name','sale_name','king_num','delivery_name,extra_type,sale_id,sale_name,project_type'];

            }

            $detail = $this->where('id',$id)->field($field)->find();

            // echo "<pre>";
            // print_r($detail);
            // echo "</pre>";
            // exit;


            if($detail){

                $business_two_type = [
                    0=>"暂无",
                    1=>"身体项目",
                    2=>"皮肤项目"
                ];
                $detail['business_two_type_text'] = $business_two_type[$detail['business_two_type']]??'暂无';
                $order_class = [
                    '0'=>'暂无',
                    '1'=>'生美',
                    '2'=>'医美',

                ];
                $detail['order_class'] = (string)$detail['order_class'];
                $detail['order_class_text'] =  $order_class[$detail['order_class']]??'暂无';
                $detail['shop_type'] = DB::name('shop')->where('shop_id',$detail['shop_id'])->value('shop_type');

                $detail['is_outreach_text'] = $detail['is_outreach'] == 1?'是':'否';
                $detail['is_experience_text'] = $detail['is_experience'] == 1?'是':'否';
                $detail['is_introduction_text'] = $detail['is_introduction'] == 1?'是':'否';

                $project_type = [
                    1=>'手术',
                    2=>'注射',
                    3=>'光电',
                    4=>'生美皮肤',
                    5=>'身体'
                ];
                $detail['project_type_name'] = isset($project_type[$detail['project_type']])?$project_type[$detail['project_type']]:'暂无';


                // var_dump($detail['is_pay']);
                $today = date('Y-m-d');

                $create_date = date('Y-m-d',strtotime($detail['create_time']));

                $refund_type_plus = $detail['refund_type_plus'] ?? '';


                if($today == $create_date && $detail['is_pay'] == '1' && $refund_type_plus != '2'){
                    // echo "允许退款";

                    $detail['is_cancel'] = '1';
                }else{
                    // echo "不许退款";

                    $detail['is_cancel'] = '0';
                }
                // exit;

                // 时间转化

                $detail['king_push_time'] = $detail['king_push_time'] ? date('Y-m-d H:i:s', $detail['king_push_time']) : '';

                $detail['deal_time'] = $detail['deal_time'] ? date('Y-m-d', $detail['deal_time']) : '';

                $detail['cancel_time'] = $detail['cancel_time'] ? date('Y-m-d H:i:s', $detail['cancel_time']) : '';

                $businessType = Db::name('customer_balance_category')->column('name','id');
                $detail['business_type']    = $businessType[$detail['business_type']]??'暂无数据';
                if($detail['business_type'] == "疤痕"&&$detail['extra_type'] == 1)
                {
                    $detail['business_type'] = "青春痘";
                }

                $detail['order_type']    = $detail['order_type'] == 1 ? "新单":'补单';
                $shanghuType=[
                    0=>"无",
                    1=>"公户",
                    2=>"私户"
                ];
                if(!empty($detail['shanghu_type']))
                {
                    $detail['shanghu_type']=$shanghuType[$detail['shanghu_type']];
                }
                $refundTypePlus=[
                    0=>"未知",
                    1=>"通联支付",
                    2=>"传统支付",
                    3=>"通联远程"
                ];
                if(!empty($detail['refund_type_plus']))
                {
                    $detail['refund_type_plus']=$refundTypePlus[$detail['refund_type_plus']];
                }

                switch ($detail['status']) {

                    case '1':

                        $detail['status_msg'] = '已退款';

                        break;

                    case '2':

                        $detail['status_msg'] = '已下推';

                        break;

                    case '3':

                        $detail['status_msg'] = '已作废';

                        break;

                    default:

                        $detail['status_msg'] = '待退款';

                        break;

                }

            }

            else{

                $this->error = '订单不存在';

                return false;

            }

            $userId  = $request['user_id'] ?? 0;

            $permission = get_user_permission_menu($userId,'order_list_tag');

            $detail['menu_list'] = $permission ? $permission : [];

            return $detail;

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];

        }

    }



    /**

     * 订单商品详情

     * @param array $request

     * @return array

     * @author SL

     * @create 2021-06-02

     */

    public function getGoodsDataDetail($request)

    {

        try {

            $id = $request['order_id'] ?? 0;

            if(!$id){

                $this->error = '请传入订单id';

                return [];

            }

            $type = $request['type'] ?? 0;

            if(!$type){

                $this->error = '请传入退款单类型';

                return [];

            }

            $detail = [];

            $list =[];

            $detail = Db::name('shop_refund_order')->field('id')->where('id',$id)->find();

            if($detail)

            {



                if (in_array($type,[1,3]))

                {

                    $field = ['id,order_id,refund_mode,refund_mode_name,bank_number,data_business_type,data_sales_policy,descs,pay_price,gift_price,shop_transfer_price,data_business_type,data_business_two_type'];

                }else

                {

                    $field = ['id,order_id,goods_id,goods_name,pay_price,kingdee_code,unit_code,goods_deal_time,is_gift,descs,house_code,house_code_name,shop_transfer_price,data_business_type,data_business_two_type'];

                }

                // 订单商品

                $detail['goodsList'] = [];

                $list = Db::name('shop_refund_order_goods')

                    ->where('order_id', $id)

                    ->order('id DESC')

                    ->field($field)->select()->toArray();

                $business_type = [
                    1=>'疤痕',
                    2=>'项目',
                    3=>'青春痘',
                    4=>'护肤品'
                ];
                $business_two_type = [
                    1=>'身体项目',
                    2=>'皮肤项目'
                ];

                foreach ($list as $key => &$value)

                {

                    $value['data_business_type_text'] = isset($business_type[$value['data_business_type']])?$business_type[$value['data_business_type']]:'';
                    $value['data_business_two_type_text'] = isset($business_two_type[$value['data_business_two_type']])?$business_two_type[$value['data_business_two_type']]:'';
                    $value['data_business_two_type'] = !empty($value['data_business_two_type']) ?$value['data_business_two_type']:'';
                    if (isset($value['goods_deal_time']))

                    {

                        $value['goods_deal_time'] = date("Y-m-d",$value['goods_deal_time']);

                    }



                }

            }

            else{

                $this->error = '订单不存在';

                return false;

            }



            if ($list) {

                $detail['goodsList'] = $list;

            }

            return $detail;

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];

        }

    }




    /* 订单修改 */
    public function updateDataDetail($request)
    {

        $order = $this->find($request['id']);


        if(empty($order))//验证订单
        {
            $this->error='订单不存在';
            return false;
        }
        if(empty($order->is_pay))
        {
            $this->error='订单未完成';
            return false;
        }
        if($order->status == 3 ){
            $this->error='该订单已经作废，无法修改';
            return false;
        }
        if(empty($request['is_experience']))//是否体验
        {
            $order->is_experience = 0;
            $order->experience_id = 0;
            $order->experience_name = "";
        }else{
            if(empty($request['experience_id']))
            {
                $this->error='未选择体验人';
                return false;
            }else{
                $staff=Db::name('shop_person')->field('id,name')->where('id',$request['experience_id'])->find();
                if(empty($staff))
                {
                    $this->error='体验人不存在';
                    return false;
                }else{
                    $order->is_experience = $request['is_experience'];
                    $order->experience_id = $request['experience_id'];
                    $order->experience_name = $staff['name'];
                }
            }
        }

        if(empty($request['is_introduction']))//是否转介绍
        {
            $order->is_introduction = 0;
            $order->introduction_id = 0;
            $order->introduction_name = "";
        }else{
            if(empty($request['introduction_id']))
            {
                $this->error='未选择转介绍人';
                return false;
            }else{
                $staff=Db::name('shop_person')->field('id,name')->where('id',$request['introduction_id'])->find();
                if(empty($staff))
                {
                    $this->error='转介绍人不存在';
                    return false;
                }else{
                    $order->is_introduction = $request['is_introduction'];
                    $order->introduction_id = $request['introduction_id'];
                    $order->introduction_name = $staff['name'];
                }
            }
        }


        if(empty($request['is_outreach']))//是否外部联系
        {
            $order->is_outreach = 0;
            $order->outreahc_id = 0;
            $order->outreahc_name = "";
        }else{
            if(empty($request['outreahc_id']))
            {
                $this->error='未选择外部联系人';
                return false;
            }else{
                $staff=Db::name('shop_person')->field('id,name')->where('id',$request['outreahc_id'])->find();
                if(empty($staff))
                {
                    $this->error='外部联系人不存在';
                    return false;
                }else{
                    $order->is_outreach = $request['is_outreach'];
                    $order->outreahc_id = $request['outreahc_id'];
                    $order->outreahc_name = $staff['name'];
                }
            }
        }

        if(empty($request['sale_id'])){
            $order->sale_id = 0;
            $order->sale_name = "";
        }else{
            $staff=Db::name('shop_person')->field('id,name')->where('id',$request['sale_id'])->find();
            if(empty($staff))
            {
                $this->error='开单人不存在';
                return false;
            }else{
                $order->sale_id = $request['sale_id'];
                $order->sale_name = $staff['name'];
            }
        }

        $alter = false;
        //当类型为青春痘时
        if($request['business_type'] == 3)
        {
            // $request['business_type']=1;
            $order->extra_type=1;
        }else{
            $order->extra_type=0;
        }


        if($order['type'] == 2 && ($request['business_type'] == 2 && !in_array($request['business_two_type'],[1,2])) ){
            $this->error='请选择业务二级分类';
            return false;
        }


        Db::startTrans();
        try {
            switch($order['type']){
                case 1:
                    //退款单
                    if(!empty($request['order_goods'])){
                        $order_goods = $request['order_goods'];
                        $business_type = $order_goods[0]['data_business_type'];
                        $business_two_type = $order_goods[0]['data_business_two_type'];
                        foreach($order_goods as $key=>&$v){
                            if($v['data_business_type'] == 2  && !in_array($v['data_business_two_type'],[1,2])){
                                throw new \Exception("请选择业务二级类型");
                                exit;
                            }
                            $oldOrderGoods = DB::name('shop_refund_order_goods')->where('id',$v['id'])->find();
                            if($oldOrderGoods['data_business_type'] != $v['data_business_type']) {
                                // 减少原来账户金额
                                $where = [
                                    'customer_id' => $order->uid,
                                    'balance_category_id'=>$oldOrderGoods['data_business_type'],
                                ];
                                $balanceOne = Db::name('customer_balance')->where($where)->find();
                                $updateData = [
                                    'money'=>$balanceOne['money']-$v['pay_price'],
                                    'complimentary_money'=>$balanceOne['complimentary_money']-$v['gift_price'],
                                    'shop_transfer_money'=>$balanceOne['shop_transfer_money']-$v['shop_transfer_price']
                                ];
                                Db::name('customer_balance')->where($where)->update($updateData);
                                // 增加修改账户金额
                                $where = [
                                    'customer_id' => $order->uid,
                                    'balance_category_id'=>$v['data_business_type'],
                                ];
                                $balanceTwo = Db::name('customer_balance')->where($where)->find();
                                $updateData = [
                                    'money'=>$balanceTwo['money']+$v['pay_price'],
                                    'complimentary_money'=>$balanceTwo['complimentary_money']+$v['gift_price'],
                                     'shop_transfer_money'=>$balanceTwo['shop_transfer_money']+$v['shop_transfer_price']
                                ];
                                Db::name('customer_balance')->where($where)->update($updateData);
                            }
                            $update['data_business_type'] = $v['data_business_type'];
                            $update['data_business_two_type'] = !in_array($v['data_business_type'],[1,3,4])?$v['data_business_two_type']:0;
                            $update['update_time'] = time();
                            $order_goods_res = Db::name('shop_refund_order_goods')->where('id',$v['id'])->update($update);
                            if(!$order_goods_res){
                                throw new \Exception("收款单单项修改失败");
                                exit;

                            }
                        }
                    }
                    break;
                case 2:

                    //退货单
                    $business_type = $request['business_type']??0;
                    $business_two_type = $request['business_two_type']??0;

                    $alter = false;
                    if($order['business_type'] != $request['business_type']) {    $alter = true;   }
                    if($alter){
                        $oldOrderBusinessType = $order['business_type'];
                        //减少原来账户金额
                        $where = [
                            'customer_id' => $order->uid,
                            'balance_category_id'=>$oldOrderBusinessType,
                        ];
                        $balanceOne = Db::name('customer_balance')->where($where)->find();
                        $updateData = [
                            'money'=>$balanceOne['money']-$order->pay_amount,
                            'complimentary_money'=>$balanceOne['complimentary_money']-$order->gift_amount,
                            'shop_transfer_money'=>$balanceOne['shop_transfer_money']-$order->shop_transfer_amount
                        ];
                        Db::name('customer_balance')->where($where)->update($updateData);

                        // 增加修改账户金额
                        $where = [
                            'customer_id' => $order->uid,
                            'balance_category_id'=>$request['business_type'],
                        ];
                        $balanceTwo = Db::name('customer_balance')->where($where)->find();
                        $updateData = [
                            'money'=>$balanceTwo['money']+$order->pay_amount,
                            'complimentary_money'=>$balanceTwo['complimentary_money']+$order->gift_amount,
                            'shop_transfer_money'=>$balanceTwo['shop_transfer_money']+$order->shop_transfer_amount
                        ];
                        Db::name('customer_balance')->where($where)->update($updateData);
                    }


                    break;
                case 3:
                    //收款单
                    if(!empty($request['order_goods'])){

                        $order_goods = $request['order_goods'];
                        $business_type = $order_goods[0]['data_business_type'];
                        $business_two_type = $order_goods[0]['data_business_two_type'];
                        foreach($order_goods as $key=>&$v){
                            if($v['data_business_type'] == 2  && !in_array($v['data_business_two_type'],[1,2])){
                                throw new \Exception("请选择业务二级类型");
                                exit;
                            }
                            $oldOrderGoods = DB::name('shop_refund_order_goods')->where('id',$v['id'])->find();
                            if($oldOrderGoods['data_business_type'] != $v['data_business_type']){
                                // 减少原来账户金额
                                $where = [
                                    'customer_id' => $order->uid,
                                    'balance_category_id'=>$oldOrderGoods['data_business_type'],
                                ];
                                $balanceOne = Db::name('customer_balance')->where($where)->find();

                                $updateData = [
                                    'money'=>$balanceOne['money']-$v['pay_price'],
                                    'complimentary_money'=>$balanceOne['complimentary_money']-$v['gift_price'],
                                    'shop_transfer_money'=>$balanceOne['shop_transfer_money']-$v['shop_transfer_price']
                                ];
                                Db::name('customer_balance')->where($where)->update($updateData);

                                // 增加修改账户金额
                                $where = [
                                    'customer_id' => $order->uid,
                                    'balance_category_id'=>$v['data_business_type'],
                                ];
                                $balanceTwo = Db::name('customer_balance')->where($where)->find();
                                $updateData = [
                                    'money'=>$balanceTwo['money']+$v['pay_price'],
                                    'complimentary_money'=>$balanceTwo['complimentary_money']+$v['gift_price'],
                                    'shop_transfer_money'=>$balanceTwo['shop_transfer_money']+$v['shop_transfer_price']
                                ];
                                Db::name('customer_balance')->where($where)->update($updateData);
                            }
                            $update['data_business_type'] = $v['data_business_type'];
                            $update['data_business_two_type'] = !in_array($v['data_business_type'],[1,3,4])?$v['data_business_two_type']:0;
                            $update['update_time'] = time();
                            $order_goods_res = Db::name('shop_refund_order_goods')->where('id',$v['id'])->update($update);
                            if(!$order_goods_res){
                                throw new \Exception("收款单单项修改失败");
                                exit;
                            }
                        }
                    }
                    break;
            }

            if(isset($business_type)){
                $order->business_type=$business_type;
            }
            if(isset($business_two_type)){
                $order->business_two_type = $business_two_type;
            }

            $order->order_type=$request['order_type'];
            $order->order_class = $request['order_class'] ?? 0;
            $res=$order->save();

            Db::name('shop_refund_order_turn')->where('vice_refund_order_no',$order['refund_order_no'])->update(['status' => 1]);

            if($res)
            {
                Db::commit();
                return ['msg'=>"更新完毕",'code'=>200];
            }else{
                Db::rollback();
                $this->error='更新失败';
                return false;
            }
        } catch (\Exception $e) {
            Db::rollback();
            $this->error = $e->getMessage();
            return [];

        }
    }





    /**

     * 创建收退款单

     * @param  array $request 请求参数

     * @return bool

     * @author LIU

     * @create 2021-12-12

     */

    public function addData($request)

    {



        try {

            $validate = new \app\shop\validate\Refund();

            if (!$validate->scene('createOrder')->check($request)) {

                $this->error = $validate->getError();

                return false;

            }

        }catch (\Exception $e) {

            $this->error = $e->getMessage();

            return false;

        }

        $request['refund_type_plus'] = $request['refund_type_plus'] ?? '2';
        if($request['refund_type_plus'] == '1'){

            //  扫码盒子支付
            $is_pay = '0';

        }elseif ($request['refund_type_plus'] == '3') {

            // echo "线上扫码支付";
            $is_pay = '0';

        }else{

            // echo "传统录单";
            $is_pay = '1';

        }


        // exit;
        // var_dump($request);
        $modes=Db::name('refund_mode')->where('status',1)->field('refund_mode,refund_mode_name')->select()->toArray();
        $modes_key = array_column($modes,null,'refund_mode');

        $modes=array_column($modes,'refund_mode');


        Db::startTrans();

        try {

            $time = time();

            $orderDataList = $request['goodsList'];

            $pay_price= [];

            $gift_price=[];

            $shop_transfer_price = [];

            $shop=Db::name('shop')->where('shop_id',$request['shop_id'])->field('type,keycode,shop_type,is_sichuan,bank_card')->find();//判断直营 加盟

            $coefficient=1;//数据统计计算系数

            $is_transfer=0;

            foreach ($orderDataList as $key => $value) {

                //服务类型判断

                if (!isset($value['refund_mode']) || empty($value['refund_mode']) || !in_array($value['refund_mode'],$modes))
                {

                    $this->error = '结算方式必填';

                    return false;

                }

                if (!isset($value['descs']) || empty($value['descs']))
                {

                    $this->error = '退款备注必填';

                    return false;

                }

                if(!in_array($value['refund_mode'],['01','06']))

                {

//                    if (!isset($value['bank_number']) || empty($value['bank_number']))
//
//                    {
//
//                        $this->error = '我方银行账号必填';
//
//                        return false;
//
//                    }

                }

                //如果有店转

                if ($value['refund_mode']=='06')

                {

                    $is_transfer=1;

                }



                $pay_price[] = $value['pay_price'];

                $gift_price[] =$value['gift_price'];

                $shop_transfer_price[] = isset($value['shop_transfer_price'])?$value['shop_transfer_price']:0;
            }

            if ($shop['type'] == 1)//直营店

            {

                //直营店门店编码 发货组织编码 销售组织编码必传

                if (!$shop['keycode']|| !isset($request['sales_organization'])|| !$request['sales_organization'] || !isset($request['settlement_organization'])|| !$request['settlement_organization'])

                {

                    $this->error = '直营店门店编码或发货组织编码或销售组织编码不存在，请联系总部解决';

                    return false;

                }

                //非川渝店

                if ($shop['is_sichuan'] == 1)

                {

                    //退款单

                    if ($request['type']==1)

                    {

                        if($shop['shop_type']==1)//如果是门诊

                        {

                            //退款调整，不做数据统计

                            if ($request['refund_type']=="101.03")

                            {

                                $coefficient=0;

                            }

//                            elseif ($request['refund_type']=="101.01")//退款店转

//                            {

//                                //是店转

//                                if ($is_transfer)

//                                {

//                                    //非疗程，扣一半

//                                   if($request['is_treatment']==2)

//                                    {

//                                        $coefficient=0.5;

//                                    }

//                                }else

//                                {

//                                    //非店转，非疗程,选择了门店，扣一半

//                                    if ($request['is_treatment']== 2 && $request['referral_shop_id'])

//                                    {

//                                        $coefficient=0.5;

//                                    }

//                                }

//                            }

                            else //退款和退款店转

                            {

                                //是店转

                                if ($is_transfer)

                                {

                                    //非疗程，扣一半

                                    if($request['is_treatment']==2)

                                    {

                                        $coefficient=0.5;

                                    }

                                }else

                                {

                                    //非店转，非疗程,选择了门店，扣一半

                                    if ($request['is_treatment']==2 && $request['referral_shop_id'])

                                    {

                                        $coefficient=0.5;

                                    }

                                }

                            }



                        }else//门店退款

                        {

                            //退款调整，不做数据统计

                            if ($request['refund_type']=="101.03")

                            {

                                $coefficient=0;

                            }elseif ($request['refund_type']=="101.01")//店转退款

                            {

                                //是店转

                                if ($is_transfer)

                                {

                                    //非疗程，扣一半

                                    if($request['is_treatment']==2)

                                    {

                                        $coefficient=0.5;

                                    }

                                }

                            }

                        }

                    }elseif ($request['type']==3)//收款单

                    {

                        if($shop['shop_type']==1)//如果是门诊

                        {

                            //收款调整，不做数据统计

                            if ($request['refund_type']=="101.03")

                            {

                                $coefficient=0;

                            }else //收款

                            {

                                //店转

                                if ($is_transfer)

                                {

                                    //非疗程，做金额对半分

                                    if($request['is_treatment']==2)

                                    {

                                        $coefficient=0.5;

                                    }

                                }else

                                {

                                    //非店转,非疗程,选择了门店做金额对半分

                                    if($request['is_treatment']==2 && $request['referral_shop_id'])

                                    {

                                        $coefficient=0.5;

                                    }

                                }



                            }



                        }else//门店收款

                        {

                            //收款调整，不做数据统计

                            if ($request['refund_type']=="101.03")

                            {

                                $coefficient=0;

                            }else //收款

                            {

                                //店转

                                if ($is_transfer)

                                {

                                    //非疗程，拆分一半

                                    if($request['is_treatment']==2)

                                    {

                                        $coefficient=0.5;

                                    }

                                }



                            }

                        }

                    }else

                    {

                        $this->error = '订单类型不正确';

                        return false;

                    }

                }

            }



            $gift_price=bcadd(array_sum($gift_price),0,2);

            $pay_price = bcadd(array_sum($pay_price),0,2);

            $shop_transfer_price = bcadd(array_sum($shop_transfer_price),0,2);

            $total_amount=bcadd(bcadd($gift_price,$pay_price,2),$shop_transfer_price,2);

            //判断金额

            if ($gift_price != $request['gift_amount'] || $pay_price != $request['pay_amount'] || $shop_transfer_price != $request['shop_transfer_amount'] )

            {

                $this->error = '订单金额不正确';

                return false;

            }

//            if($request['business_type'] == 2 && !in_array($request['business_two_type'],[1,2])){
//                $this->error = '请选择二级项目分类';
//
//                return false;
//            }

            $operator_name= Db::name('admin_user')->where(['id' => $request['operator_id']])->value('realname');

            $customer_data= Db::name('customer')->where('id',$request['uid'])->field('source_id,source_type_id')->find();
            // 验证

            $data = [

                'uid'               => trim($request['uid']), // 客户

                'uid_source_type_id' => $customer_data['source_type_id']??0,

                'source_id'  => $customer_data['source_id']??0,

                'consignee'         => trim($request['consignee']), // 收货人

                'refund_order_no'          => $this->getOrderNo(), // 订单号

                'sale_id'           => $request['sale_id'], // 销售员id

                'sale_name'           => trim($request['sale_name']), // 销售员姓名

                'shop_id'           => $request['shop_id'], // 门店id

                'shop_name'           => trim($request['shop_name']), // 门店名称

                'referral_shop_id'       => isset($request['referral_shop_id']) ? $request['referral_shop_id'] : 0, // 转诊门店id

                'referral_shop_name'       => isset($request['referral_shop_name']) ? $request['referral_shop_name'] : '', // 转诊门店名称

                'coefficient'           => $coefficient, // 统计数据计算系数

                'shop_type'           => $shop['shop_type'], // 门店属性

                'is_treatment'           => $request['is_treatment'], // 是否疗程  1是  2否 0未选择

                'operator_id'       => $request['operator_id'],//制单员id

                'operator_name'       => $operator_name,//制单员姓名

                'create_time'       => $time, // 创建时间

                'deal_time'         => strtotime($request['deal_time']), // 成交日期

                'total_amount'      =>  isset($request['total_amount']) ? $request['total_amount'] : 0, // 应退（收）金额

                'pay_amount'        => isset($request['pay_amount']) ? $request['pay_amount'] : 0, // 实退（收）本金

                'gift_amount'        => isset($request['gift_amount']) ? $request['gift_amount'] : 0, // 实退（收）赠金

                'shop_transfer_amount' => isset($request['shop_transfer_amount']) ? $request['shop_transfer_amount'] : 0, // 实退（收）店转

                'description'                => isset($request['description']) ? $request['description'] : '', // 订单描述

                'order_type'                => $request['order_type'], // 订单类型 1新单 2补单

                'business_type'                => $request['business_type'], // 业务类型 1项目 2疤痕 3青春痘 4护肤品

                'sales_policy'                => isset($request['sales_policy'])? $request['sales_policy'] : '', // 销售政策编码

                'refund_type'                => isset($request['refund_type'])? $request['refund_type'] : '', // 退款类型 101.01 店转  101.02 退款

                'type'             => $request['type'],//退款单类型 1退款单 2退货单

                'market_id'       => isset($request['market_id']) ? $request['market_id'] : 0, // 市场id

                'market_name'       => isset($request['market_name']) ? $request['market_name'] : '', // 市场名称

                'sales_organization'       => isset($request['sales_organization']) ? $request['sales_organization'] : 0, // 销售组织编码

                'sales_name'       => isset($request['sales_name']) ? $request['sales_name'] : '', // 销售组织名称

                'settlement_organization'       => isset($request['settlement_organization']) ? $request['settlement_organization'] : 0, // 结算组织编码

                'settlement_name'       => isset($request['settlement_name']) ? $request['settlement_name'] : '', // 结算组织名称

                'is_experience'     => $request['is_experience'], // 是否体验 0否 1是

                'experience_id'       => isset($request['experience_id']) ? $request['experience_id'] : 0, // 体验人id

                'experience_name'       => isset($request['experience_name']) ? $request['experience_name'] : '', // 体验人姓名

                'is_outreach'       => $request['is_outreach'], // 是否外联 0否 1是

                'outreahc_id'       => isset($request['outreahc_id']) ? $request['outreahc_id'] : 0, // 外联人id

                'outreahc_name'       => isset($request['outreahc_name']) ? $request['outreahc_name'] : '', // 外联人姓名

                'is_introduction'       => $request['is_introduction'], // 是否转介绍 0否 1是

                'introduction_id'       => isset($request['introduction_id']) ? $request['introduction_id'] : 0, // 转介绍人id

                'introduction_name'       => isset($request['introduction_name']) ? $request['introduction_name'] : '', // 转介绍人姓名

                'combo'       => isset($request['combo']) ? $request['combo'] : 0, // 退款审批类型 0没选   1项目退款 2疤痕退款

                'refund_type_plus'           => $request['refund_type_plus'] ?? '', // 收款方式2

                'shanghu_type'           => $request['shanghu_type'] ?? '', // 商户分类1是公户，2是私户

                'is_pay'           => $is_pay, // 是否支付：0未支付，1已支付

                'order_class' => $request['order_class'] ?? 0, //订单分类   1 生美 2 医美 仅限门诊

                'refunder' => $request['refunder'] ?? '', //退款人

                'refund_account' => $request['refund_account'] ?? '', //退款账号

//                'business_two_type' => $request['business_two_type'] ?? 0, //业务二级分类

            ];
            //当类型为青春痘时
            if($data['business_type'] == 3)
            {
                //$data['business_type']=1;
                $data['extra_type']=1;
            }else{
                $data['extra_type']=0;
            }
            // 需要放开
            $order = $this->create($data);
            $oneBalance  =  $onegiftBalance = $oneShopBalance  = [];
            $twoBalance  =  $twogiftBalance = $twoShopBalance  = [];
            $threeBalance = $threegiftBalance = $threeShopBalance  = [];
            $fourBalance  = $fourgiftBalance = $fourShopBalance  = [];
//            var_dump($shop['bank_card']);die;
            if ($order) {

                $business_type = $orderDataList[0]['business_type']??0;
                $business_two_type = $orderDataList[0]['bussiness_two_type'] ??0;
                $update['business_type'] = $business_type;
                $update['business_two_type'] = $business_two_type;

                Db::name('shop_refund_order')->where('id',$order->id)->update($update);

//                var_dump($orderDataList);die;
                foreach ($orderDataList as $k => $v) {
                    $business_two_type = isset($v['business_two_type'])?$v['business_two_type']:0;
                    if($v['business_type'] == 2 && !in_array($business_two_type,[1,2])){
                        $this->error = '请选择业务二级分类';
                        return false;
                    }
                    $orderGoodsList[$k]['order_id'] = $order->id;

                    $orderGoodsList[$k]['create_time'] = $time;

                    $orderGoodsList[$k]['refund_mode'] = $v['refund_mode'];

                    $orderGoodsList[$k]['refund_mode_name'] = isset($modes_key[$v['refund_mode']])?$modes_key[$v['refund_mode']]['refund_mode_name']:"";

                    $orderGoodsList[$k]['bank_number'] = $shop['bank_card'];

                    $orderGoodsList[$k]['data_business_type'] = isset($v['business_type'])?$v['business_type']:0;

                    if($orderGoodsList[$k]['data_business_type'] == 2){
                        $orderGoodsList[$k]['data_business_two_type'] = isset($v['business_two_type'])?$v['business_two_type']:0;
                    }else{
                        $orderGoodsList[$k]['data_business_two_type'] = 0;
                    }

                    $orderGoodsList[$k]['data_sales_policy'] =isset($v['data_sales_policy'])?$v['data_sales_policy']:"";

                    $orderGoodsList[$k]['pay_price'] = $v['pay_price'] ?? 0;

                    $orderGoodsList[$k]['gift_price'] = $v['gift_price'] ?? 0;

                    $orderGoodsList[$k]['shop_transfer_price'] = isset($v['shop_transfer_price']) ? $v['shop_transfer_price']:0;

                    switch ($orderGoodsList[$k]['data_business_type']){
                        case  1:
                            array_push($oneBalance,$orderGoodsList[$k]['pay_price']);
                            array_push($onegiftBalance,$orderGoodsList[$k]['gift_price']);
                            array_push($oneShopBalance,$orderGoodsList[$k]['shop_transfer_price']);
                            break;
                        case  2:
                            array_push($twoBalance,$orderGoodsList[$k]['pay_price']);
                            array_push($twogiftBalance,$orderGoodsList[$k]['gift_price']);
                            array_push($twoShopBalance,$orderGoodsList[$k]['shop_transfer_price']);
                            break;
                        case  3:
                            array_push($threeBalance,$orderGoodsList[$k]['pay_price']);
                            array_push($threegiftBalance,$orderGoodsList[$k]['gift_price']);
                            array_push($threeShopBalance,$orderGoodsList[$k]['shop_transfer_price']);
                            break;
                        case  4:
                            array_push($fourBalance,$orderGoodsList[$k]['pay_price']);
                            array_push($fourgiftBalance,$orderGoodsList[$k]['gift_price']);
                            array_push($fourShopBalance,$orderGoodsList[$k]['shop_transfer_price']);
                            break;

                    }

                    $orderGoodsList[$k]['descs'] = $v['descs'];


                }
//                echo 111;die;
                // 需要放开
                Db::name('shop_refund_order_goods')->insertAll($orderGoodsList);

                // 添加操作记录

                $content = '创建退款订单：【'. $operator_name . '】创建了【' . $request['consignee'] . '】' . '的订单，退款订单号：【' . $data['refund_order_no'] . '】';

                $code = [];

                $code = $data;

                $code['orderGoodsList']  = $orderGoodsList;

                // 需要放开
                $this->addActionRecord($request['operator_id'],'shop_refund_order_create',$order->id,$content,'shop','refund',json_encode($code));



                if($is_pay == '1'){ // 判断是否已经支付开始

                    $updateCusetomer = [

                        'final_consumption' => time(),

                        'final_consumption_money' => $data['total_amount'],

                    ];

                    Db::name('customer')->where('id','=',$data['uid'])->update($updateCusetomer);


                    // 处理客户的余额 //

                    $customerModel = new \app\crm\model\Customer();

                    $customer_id   = $data['uid'];    // 客户的id

                    // 新增 青春痘 和皮肤
                    // if( $data['business_type'] == 1 || $data['business_type'] == 3){

                    // 	$business_type = 1;

                    // }else{

                    // 	$business_type = 2;

                    // }

                    $business_type = $data['business_type'];


                    $balanceData   = [                // 余额变更数据集

                        'change_type'  => $data['type'] == 1?2:1,      // 变动类型 1:增加 2:减少
                        // 变更的余额的类型 1:疤痕 2:项目 3:青春痘 4:护肤品
                        'changeData' => [
                            ['balance_category_id'=>1,'change_money'=>array_sum($oneBalance),'complimentary_money'=>array_sum($onegiftBalance),'shop_transfer_money'=>array_sum($oneShopBalance)],
                            ['balance_category_id'=>2,'change_money'=>array_sum($twoBalance),'complimentary_money'=>array_sum($twogiftBalance),'shop_transfer_money'=>array_sum($twoShopBalance)],
                            ['balance_category_id'=>3,'change_money'=>array_sum($threeBalance),'complimentary_money'=>array_sum($threegiftBalance),'shop_transfer_money'=>array_sum($threeShopBalance)],
                            ['balance_category_id'=>4,'change_money'=>array_sum($fourBalance),'complimentary_money'=>array_sum($fourgiftBalance),'shop_transfer_money'=>array_sum($fourShopBalance)],
                        ]
                    ];

                    //新增新单判断条件，仅限门诊，选择生美，是500 医美是1000
                    $new_order_cardinal_num = 500;
                    if(in_array($request['order_class'],[1,2])&& $request['order_type'] ==1){
                        $new_order_cardinal_num = $request['order_class'] == 2 ? 1000 : 500;
                    }


                    $newOrderData  = [   // 新单变更数据集

                        'cj_time'  => ($data['type']==3 && $data['order_type']==1 && $pay_price>=$new_order_cardinal_num)?$data['deal_time']:0,     // 成交时间-时间戳

                        'cj_money'    => $pay_price,    // 成交金额

                        'cj_order_id' => $order->id, // 成交的订单单号
                    ];

                    $orderInfo     = [       // 本次需要新增的订单金额

                        'order_amount' => $pay_price, // 本次订单金额

                        'order_time'   => $data['type']==3? $data['deal_time'] : 0,   // 本次订单的时间-时间戳

                    ];
                    if($data['type']==1&&$request['refund_type']=="101.02")
                    {
                        $orderInfo     = [       // 本次需要新增的订单金额

                            'order_amount' => 0-$pay_price, // 本次订单金额

                            'order_time'   => $data['deal_time'] ?? 0,   // 本次订单的时间-时间戳

                        ];
                    }
                    $member_products = 0; // 购买了几次会员商品

                    $yhjOrderInfo  = [    // 本次需要处理的优惠卷

                        'yhj_id '     => 0,      // 本次优惠卷的id

                        'order_id  '  => 0,   // 本次订单的id

                        'operator_id' => 0,  // 核销人的id

                    ];

                    // 处理客户的余额  新单等信息 //
                    $customerModel->processingFunds($customer_id,$balanceData,$request['deal_time'],$newOrderData,$orderInfo,$yhjOrderInfo,$member_products);

                    // 金蝶推送云星空订单  //
                    //$shop['type'] = 2;
                    if ($shop['type'] != 2) {
//                        echo "111";
                        $res = $customerModel->pushKingCustomer($customer_id);
//                        echo "222";
                        if ($res == false) {

                            $this->error = $customerModel->getError();

                            return false;

                        }
//                        echo "333";
                        $kingDee = new Kingdee();

                        //收款单

                        if ($request['type']==3)

                        {

                            $result=$kingDee->receipt_money($order->id);

                        }else{

                            //退款单

                            $result=$kingDee->refund_money($order->id);

                        }
//                        echo "444";
                        if ($result['code'])

                        {

                            $this->error = $result['msg'];

                            return false;

                        }
//                        echo "555";
//                        exit;
                    }else{
                        //加盟店 不推送云星空 订单 只调整 客户的状态
                        Db::name('shop_refund_order')->where(['id' => $order->id])->update(['status' => 2]);
                    }

                    // 判断是否已经支付结束

                    $this->error = '创建成功';

                }else{

                    $this->error = '创建成功!';

                }



                // 记录最新收款时间
                $addLogModel = new AddOrderLog();

                $deal_time = strtotime($request['deal_time']);

                $addLogModel->addData($data['uid'],$request['shop_id'],$order->refund_order_no,$deal_time,'3');

                // exit;


                Db::commit();

                // $this->error = '创建成功';

                return true;

            }

        } catch (\Exception $e) {

            Db::rollback();

            $this->error = $e->getMessage();

            return false;

        }

        $this->error = '创建失败';

        return false;

    }






    /**

     * 创建退货单

     * @param  array $request 请求参数

     * @return bool

     * @author LIU

     * @create 2021-10-25

     */

    public function addGoodsData($request)

    {

        try {

            $validate = new \app\shop\validate\Refund();

            if (!$validate->scene('createGoods')->check($request)) {

                $this->error = $validate->getError();

                return false;

            }

        }catch (\Exception $e) {

            $this->error = $e->getMessage();

            return false;

        }

        Db::startTrans();

        try {

            $time = time();

            $orderDataList = $request['goodsList'];

            $goods_price= [];

            $payAmount = [];

            $shop=Db::name('shop')->where('shop_id',$request['shop_id'])->field('type,keycode')->find();//判断直营 加盟

            //直营店门店编码 发货组织编码 销售组织编码必传

            if ($shop['type'] == 1)

            {

                if (!$shop['keycode']|| !isset($request['sales_organization'])|| !$request['sales_organization'] || !isset($request['settlement_organization'])|| !$request['settlement_organization'])

                {

                    $this->error = '直营店门店编码或发货组织编码或销售组织编码不存在，请联系总部解决';

                    return false;

                }

            }

            foreach ($orderDataList as $key => $value) {

                if (!isset($value['descs']) || empty($value['descs']))

                {

                    $this->error = '退款备注必填';

                    return false;

                }

                if (!isset($value['kingdee_code']) || empty($value['kingdee_code']))

                {

                    $this->error = '商品必须选择';

                    return false;

                }

                if (!isset($value['unit_code']) || empty($value['unit_code']))

                {

                    $this->error = '单位编码必须填写';

                    return false;

                }

                if (!isset($value['number']) || empty($value['number']))

                {

                    $this->error = '退货数量必须填写';

                    return false;

                }

                if (!isset($value['house_code']) || empty($value['house_code']))

                {

                    $this->error = '退款仓库必须选择';

                    return false;

                }

                $payAmount[] = bcmul(abs($value['pay_price']), $value['number'], 2);

                $goods_price[] = bcmul($value['goods_price'], $value['number'], 2);

            }

            //判断金额

            $money=array_sum($payAmount);

            if ($request['total_amount'] != bcadd(bcadd($request['pay_amount'],$request['gift_amount'],2),$request['shop_transfer_amount'],2) ||$request['total_amount'] != $money)

            {

                $this->error = '订单金额不正确';

                return false;

            }

            $goods_price=array_sum($goods_price);

            $operator_name= Db::name('admin_user')->where(['id' => $request['operator_id']])->value('realname');

            // if($request['business_type'] == 3){

            //     $request['business_type'] == 1;

            // }

            // if($request['business_type'] == 4){

            //     $request['business_type'] == 2;

            // }

            // 验证

            $data = [

                'uid'               => trim($request['uid']), // 客户

                'consignee'         => trim($request['consignee']), // 收货人

                'refund_order_no'          => $this->getOrderNo(), // 订单号

                'shop_id'           => $request['shop_id'], // 门店id

                'shop_name'           => trim($request['shop_name']), // 门店名称

                'operator_id'       => $request['operator_id'],//制单员id

                'operator_name'       => $operator_name,//制单员姓名

                'create_time'       => $time, // 创建时间

                'deal_time'         => strtotime($request['deal_time']), // 成交日期

                'goods_price'      => $goods_price, // 订单标准金额

                'total_amount'      =>  isset($request['total_amount']) ? $request['total_amount'] : 0, // 实退金额

                'gift_amount'      =>  isset($request['gift_amount']) ? $request['gift_amount'] : 0, // 实退赠金

                'pay_amount'        => isset($request['pay_amount']) ? $request['pay_amount'] : 0, // 实退本金

                'shop_transfer_amount' => isset($request['shop_transfer_amount']) ? $request['shop_transfer_amount'] : 0, // 实退店转

                'description'                => isset($request['description']) ? $request['description'] : '', // 订单描述

                'order_type'                => $request['order_type'], // 订单类型 1新单 2补单

                'project_type'            => isset($request['project_type']) ? $request['project_type'] : 0, // 订单类型

                'business_type'                => $request['business_type'], // 业务类型 1项目 2疤痕 3青春痘 4护肤品

                'income_type'                => $request['income_type'], // 收入类型 1 服务（各类疗程卡项及疗程卡项赠送产品）2 产品销售（单独付费购买产品）3 医美收入

                'sales_policy'                => isset($request['sales_policy'])? $request['sales_policy'] : '', // 销售政策编码

                'type'             => $request['type'],//退款单类型 1退款单 2退货单

                'market_id'       => isset($request['market_id']) ? $request['market_id'] : 0, // 市场id

                'market_name'       => isset($request['market_name']) ? $request['market_name'] : 0, // 市场名称

                'sales_organization'       => isset($request['sales_organization']) ? $request['sales_organization'] : 0, // 销售组织编码

                'sales_name'       => isset($request['sales_name']) ? $request['sales_name'] : '', // 销售组织名称

                'settlement_organization'       => isset($request['settlement_organization']) ? $request['settlement_organization'] : 0, // 结算组织编码

                'settlement_name'       => isset($request['settlement_name']) ? $request['settlement_name'] : '', // 结算组织名称

                'is_experience'     => $request['is_experience'], // 是否体验 0否 1是

                'experience_id'       => isset($request['experience_id']) ? $request['experience_id'] : 0, // 体验人id

                'experience_name'       => isset($request['experience_name']) ? $request['experience_name'] : '', // 体验人姓名

                'is_outreach'       => $request['is_outreach'], // 是否外联 0否 1是

                'outreahc_id'       => isset($request['outreahc_id']) ? $request['outreahc_id'] : 0, // 外联人id

                'outreahc_name'       => isset($request['outreahc_name']) ? $request['outreahc_name'] : '', // 外联人姓名

                'is_introduction'       => $request['is_introduction'], // 是否转介绍 0否 1是

                'introduction_id'       => isset($request['introduction_id']) ? $request['introduction_id'] : 0, // 转介绍人id

                'introduction_name'       => isset($request['introduction_name']) ? $request['introduction_name'] : '', // 转介绍人姓名

                'sale_id'           => $request['sale_id'], // 销售员id

                'sale_name'           => trim($request['sale_name']), // 销售员姓名

                'delivery_name'       => isset($request['delivery_name']) ? $request['delivery_name'] : '', // 库存部门名称

                'delivery_king'       => isset($request['delivery_king']) ? $request['delivery_king'] : '', // 库存部门编码

                'business_two_type'  => isset($request['business_two_type']) ?$request['business_two_type'] : 0 ,//业务二级分类

            ];

            $order = $this->create($data);

            if ($order) {

                foreach ($orderDataList as $k => $v) {

                    $orderGoodsList[$k]['order_id'] = $order->id;

                    $orderGoodsList[$k]['create_time'] = $time;

                    $orderGoodsList[$k]['goods_id'] = $v['id'];

                    $orderGoodsList[$k]['goods_name'] = $v['name'];

                    $orderGoodsList[$k]['kingdee_code'] = $v['kingdee_code'];

                    $orderGoodsList[$k]['goods_price'] = $v['goods_price'];

                    $orderGoodsList[$k]['pay_price'] = isset($v['pay_price']) ? $v['pay_price'] : 0;

                    $orderGoodsList[$k]['spec_name'] = $v['spec_name'];

                    $orderGoodsList[$k]['unit_code'] = $v['unit_code'];

                    $orderGoodsList[$k]['number'] = $v['number'];

                    $orderGoodsList[$k]['descs'] = $v['descs'];

                    $orderGoodsList[$k]['goods_deal_time'] = isset($v['goods_deal_time']) ? strtotime($v['goods_deal_time']) : 0;

                    $orderGoodsList[$k]['is_gift'] = isset($v['is_gift']) ? $v['is_gift'] : 0;

                    $orderGoodsList[$k]['house_code'] = $v['house_code'];

                    $orderGoodsList[$k]['is_project'] = $v['is_project'];//是否服务 1 否 2是

                    $orderGoodsList[$k]['house_code_name'] = isset($v['house_code_name']) ? $v['house_code_name'] : '';

                }

                Db::name('shop_refund_order_goods')->insertAll($orderGoodsList);



                // 添加操作记录

                $content = '创建退款订单：【'. $operator_name . '】创建了【' . $request['consignee'] . '】' . '的订单，退款订单号：【' . $data['refund_order_no'] . '】';

                $code = [];

                $code = $data;

                $code['orderGoodsList']  = $orderGoodsList;

                $this->addActionRecord($request['operator_id'],'shop_refund_order_create',$order->id,$content,'shop','refund',json_encode($code));

                // 处理客户的余额 //
                $oneBalance  =  $onegiftBalance = $oneShopBalance  = [];
                $twoBalance  =  $twogiftBalance = $twoShopBalance  = [];
                $threeBalance = $threegiftBalance = $threeShopBalance  = [];
                $fourBalance  = $fourgiftBalance = $fourShopBalance  = [];

                switch ($data['business_type']){
                    case  1:
                        array_push($oneBalance,$data['pay_amount']);
                        array_push($onegiftBalance,$data['gift_amount']);
                        array_push($oneShopBalance,$data['shop_transfer_amount']);
                        break;
                    case  2:
                        array_push($twoBalance,$data['pay_amount']);
                        array_push($twogiftBalance,$data['gift_amount']);
                        array_push($twoShopBalance,$data['shop_transfer_amount']);
                        break;
                    case  3:
                        array_push($threeBalance,$data['pay_amount']);
                        array_push($threegiftBalance,$data['gift_amount']);
                        array_push($threeShopBalance,$data['shop_transfer_amount']);
                        break;
                    case  4:
                        array_push($fourBalance,$data['pay_amount']);
                        array_push($fourgiftBalance,$data['gift_amount']);
                        array_push($fourShopBalance,$data['shop_transfer_amount']);
                        break;
                }

                $customerModel = new \app\crm\model\Customer();

                $customer_id   = $data['uid'];    // 客户的id

                $balanceData   = [                // 余额变更数据集

                    'change_type'  => 1,      // 变动类型 1:增加 2:减少

                    // 变更的余额的类型 1:疤痕 2:项目 3:青春痘 4:护肤品
                    'changeData' => [
                        ['balance_category_id'=>1,'change_money'=>array_sum($oneBalance),'complimentary_money'=>array_sum($onegiftBalance),'shop_transfer_money'=>array_sum($oneShopBalance)],
                        ['balance_category_id'=>2,'change_money'=>array_sum($twoBalance),'complimentary_money'=>array_sum($twogiftBalance),'shop_transfer_money'=>array_sum($twoShopBalance)],
                        ['balance_category_id'=>3,'change_money'=>array_sum($threeBalance),'complimentary_money'=>array_sum($threegiftBalance),'shop_transfer_money'=>array_sum($threeShopBalance)],
                        ['balance_category_id'=>4,'change_money'=>array_sum($fourBalance),'complimentary_money'=>array_sum($fourgiftBalance),'shop_transfer_money'=>array_sum($fourShopBalance)],
                    ],

                    'change_money' => $data['pay_amount'],      // 变更的本金

                    'complimentary_money' => $data['gift_amount'],  // 变更的赠金

                    'shop_transfer_money' => $data['shop_transfer_amount'] , //变更的店转

                    'balance_category_id' => $data['business_type'] // 变更的余额的类型 1:疤痕 2:项目 3:青春痘 4:护肤品

                ];



                $customerModel->processingFunds($customer_id,$balanceData,$request['deal_time']);

                // exit;

                // 处理客户的余额 //

                // 客户推送金蝶

                if ($shop['type'] != 2)

                {

                    $res = $customerModel->pushKingCustomer($customer_id);

                    if($res == false){

                        $this->error = $customerModel->getError();

                        return false;

                    }

                    $kingDee = new Kingdee();

                    //退货单

                    $result=$kingDee->refund_goods($order->id);

                    if ($result['code'])

                    {

                        $this->error = $result['msg'];

                        return false;

                    }

                }

                Db::commit();

                $this->error = '创建成功';

                return true;

            }

        } catch (\Exception $e) {

            Db::rollback();

            $this->error = $e->getMessage();

            return false;

        }

        $this->error = '创建失败';

        return false;

    }





    /**

     * 修改订单基本信息

     * @param array $request 请求参数

     * @return bool

     * @author SL

     * @create 2021-06-03

     */

    public function saveData($request)

    {

        // 验证

        try{

            $validate = new \app\shop\validate\Refund();

            if (!$validate->scene('update')->check($request)) {

                $this->error = $validate->getError();

                return false;

            }

        }catch(\Exception $e){

            $this->error =$e->getMessage();

            return false;

        }

        $id = $request['order_id'] ?? 0;

        if (!$id) {

            $this->error = '参数错误';

            return false;

        }



        $order = Db::name('shop_refund_order')->where('id',$id)->find();

        if(!$order)

        {

            $this->error = '订单不存在';

            return false;

        }

        if($order['status'])

        {

            $this->error = '订单当前不可修改';

            return false;

        }



        try {

            $time = time();

            $data = [

                'house_id'     => isset($request['house_id']) ? trim($request['house_id']) : '', // 仓库

                'consignee'    => isset($request['consignee']) ? trim($request['consignee']) : '', // 收货人

                'mobile'       => isset($request['mobile']) ? trim($request['mobile']) : '', // 收货人手机号

                'province'     => isset($request['province']) ? trim($request['province']) : '', // 省

                'city'         => isset($request['city']) ? trim($request['city']) : '', // 市

                'district'     => isset($request['district']) ? trim($request['district']) : '', // 区

                'address'      => isset($request['address']) ? trim($request['address']) : '', // 收货地址

                'description'  => isset($request['description']) ? trim($request['description']) : '', // 订单备注

                'update_time'  => $time, // 创建时间

            ];



            $bool = $this->where(['id'=>$id])->update($data);

            if ($bool !== false)

            {

                // 添加操作记录

                $content = '';

                if($order['house_id'] != $data['house_id'])

                {

                    $where = [];

                    $house_ids = [$order['house_id'],$data['house_id']];

                    $where = [

                        ['id','in', $house_ids]

                    ];

                    $house_name = Db::name('shop_warehouse')->where($where)->column('name','id');

                    $content .= '将发货仓库【' . $house_name[$order['house_id']] . '】修改为【' . $house_name[$data['house_id']] . '】；';

                }

                if($order['province'] != $data['province'] || $order['city'] != $data['city'] || $order['district'] != $data['district'])

                {

                    $where = [];

                    $region_ids = [$order['province'],$order['city'],$order['district'],$data['province'],$data['city'],$data['district']];

                    $where = [

                        ['id', 'in', $region_ids]

                    ];

                    $region = Db::name('shop_region')->where($where)->column('name','id');

                    $content .= '将收货地址【' . $region[$order['province']]. $region[$order['city']] .$region[$order['district']] . '】修改为【' . $region[$data['province']] . $region[$data['city']] . $region[$data['district']] . '】；';

                }

                if($order['address'] != $data['address'])

                {

                    $content .= '将详细地址【' . $order['address'] . '】修改为【' . $data['address'] . '】；';

                }

                if($order['consignee'] != $data['consignee'])

                {

                    $content .= '将联系人【' . $order['consignee'] . '】修改为【' . $data['consignee'] . '】；';

                }

                if($order['mobile'] != $data['mobile'])

                {

                    $content .= '将手机号【' . $order['mobile'] . '】修改为【' . $data['mobile'] . '】；';

                }

                if($order['description'] != $data['description'])

                {

                    $content .= '将订单备注【' . $order['description'] . '】修改为【' . $data['description'] . '】；';

                }



                if ($content)

                {

                    $code = json_encode($data);

                    $this->addActionRecord($request['operator_id'], 'shop_refund_order_update', $id, $content, 'shop', 'order', $code);

                }



                $this->error = '更新成功';

                return true;

            }

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return false;

        }

        $this->error = '更新失败';

        return false;

    }



    /**

     * 修改订单商品

     * @param  array $request 请求参数

     * @return bool

     * @author SL

     * @create 2021-06-05

     */

    public function saveOrderGoodsData($request)

    {

        try {

            $order_id = $request['order_id'] ?? 0; // 订单id

            $opType = $request['op_type'] ?? 0; // 操作类型 1-增加商品 2-修改商品 3-删除商品

            if (!$order_id || !$opType) {

                $this->error = '参数错误';

                return false;

            }

            $order = Db::name('shop_refund_order')->where('id',$order_id)->find();

            if(!$order)

            {

                $this->error = '订单不存在';

                return false;

            }

            if($order['status'])

            {

                $this->error = '订单当前不能修改';

                return false;

            }

            // 操作成功状态

            $saveBool = false;

            $time = time();

            // 增加商品

            if($opType == 1)

            {

                $orderGoodsListArr = isset($request['goodsList']) && $request['goodsList'] ? $request['goodsList'] : [];



                if(!$orderGoodsListArr)

                {

                    $this->error = '参数错误';

                    return false;

                }



                // 验证商品价格

                $goods_ids = array_column($orderGoodsListArr, 'id');



                // 获取商品价格

                $where = [];

                $where = [

                    ['g.id','in', $goods_ids]

                ];

                $field = 'g.id, gs.price, gs.kingdee_code,gs.small_unit_price';

                $goodsInfo = Db::name('shop_goods')

                    ->alias('g')

                    ->join(['shrimp_shop_goods_sku' =>'gs'],'g.id=gs.goods_id')

                    ->where($where)

                    ->field($field)

                    ->select()->toArray();

                $goodsInfo = array_column($goodsInfo, null, 'id');

                $gwhere = [];

                $gwhere = [

                    ['goods_id','in', $goods_ids],

                    ['customer_id','=',$order['uid']]

                ];

                $goodsPrice = Db::name('shop_goods_price')->where($gwhere)->column('price','goods_id');



                $error = '';

                //判断小包装规格 无需对比价目表

                if(!empty($orderGoodsListArr)){

                    $unitCodeList = array_column($orderGoodsListArr,'unit_code');

                    $unitCodeList && $unitCodeList = Db::name('shop_goods_unit')->where('small_unit_code','in',$unitCodeList)->column('unit_id','small_unit_code');

                }

                foreach ($orderGoodsListArr as $key => $value) {

                    if(!isset($value['number']) || empty($value['number']))

                    {

                        $this->error = '请填写销售数量';

                        return false;

                    }

                    if(!isset($goodsPrice[$value['id']]))

                    {

                        $goodsPrice[$value['id']] = $goodsInfo[$value['id']]['price'];

                    }

                    //判断小包装规格 无需对比价目表

                    if(!isset($unitCodeList[$value['unit_code']])){//大包装

                        if($value['customer_price'] != $goodsPrice[$value['id']])

                        {

                            $error .= '商品【' . $value['name'] . '】价目表价格有变动；';

                        }

                        if($value['price'] != $goodsInfo[$value['id']]['price'])

                        {

                            $error .= '商品【' . $value['name'] . '】价格有变动；';

                        }

                    }else{//小包装

                        if($value['price'] != $goodsInfo[$value['id']]['small_unit_price'])

                        {

                            $error .= '商品【' . $value['name'] . '】价格有变动；';

                        }

                    }

                    if($value['kingdee_code'] != $goodsInfo[$value['id']]['kingdee_code'])

                    {

                        $error .= '商品【' . $value['name'] . '】金蝶编码有变动；';

                    }

                }

                if($error)

                {

                    $this->error = $error;

                    return false;

                }



                foreach ($orderGoodsListArr as $k => $v) {

                    $orderGoodsList[$k]['order_id'] = $order_id;

                    $orderGoodsList[$k]['create_time'] = $time;

                    $orderGoodsList[$k]['goods_id'] = $v['id'];

                    $orderGoodsList[$k]['goods_name'] = $v['name'];

                    $orderGoodsList[$k]['kingdee_code'] = $v['kingdee_code'];

                    $orderGoodsList[$k]['goods_price'] = $v['price'];

                    $orderGoodsList[$k]['pay_price'] = $v['customer_price'];

                    $orderGoodsList[$k]['sku_id'] = $v['sku_id'];

                    $orderGoodsList[$k]['item_id'] = $v['item_id'];

                    $orderGoodsList[$k]['item_name'] = $v['item_name'];

                    $orderGoodsList[$k]['unit_id'] = $v['unit_id'];

                    $orderGoodsList[$k]['unit_name'] = $v['unit_name'];

                    $orderGoodsList[$k]['number'] = $v['number'];

                }



                $bool = Db::name('shop_refund_order_goods')->insertAll($orderGoodsList);

                if($bool !== false)

                {

                    // 添加操作记录

                    $goods_name = array_column($orderGoodsList, 'goods_name');

                    $goods_name_str = implode('|', $goods_name);

                    $content = '添加订单商品：【' . $goods_name_str . '】';

                    $code = [];

                    $code['order_id'] = $order_id;

                    $code['orderGoodsList']  = $orderGoodsList;

                    $this->addActionRecord($request['operator_id'],'shop_refund_order_goods',$order_id,$content,'shop','order',json_encode($code));



                    $this->error = '添加订单商品成功';



                    $saveBool = true;

                }

            }

            // 修改商品

            elseif($opType == 2)

            {

                $order_goods_id = isset($request['order_goods_id']) && $request['order_goods_id'] ? $request['order_goods_id'] : '';

                $number = isset($request['number']) && $request['number'] ? $request['number'] : '';

                if (!$order_goods_id || !$number) {

                    $this->error = '参数错误';

                    return false;

                }



                $orderGoods = Db::name('shop_refund_order_goods')->where('id',$order_goods_id)->find();

                if(!$orderGoods)

                {

                    $this->error = '订单商品不存在';

                    return false;

                }



                if(!isset($request['number']) || empty($request['number']))

                {

                    $this->error = '请填写销售数量';

                    return false;

                }



                $goodsData = [

                    'number'     => isset($request['number']) ? trim($request['number']) : 1, // 商品数量

                ];



                $bool = Db::name('shop_refund_order_goods')->where(['id'=>$order_goods_id])->update($goodsData);

                if ($bool !== false) {

                    // 添加操作记录

                    $content = '将商品【' . $orderGoods['goods_name'] . '】数量【' . $orderGoods['number'] . '】修改为【' . $number . '】';

                    $this->addActionRecord($request['operator_id'],'shop_refund_order_goods',$order_id,$content,'shop','order',json_encode($orderGoods));



                    $this->error = '更新订单商品成功';



                    $saveBool = true;

                }

            }

            elseif($opType == 3)

            {

                $order_goods_id = isset($request['order_goods_id']) && $request['order_goods_id'] ? $request['order_goods_id'] : '';

                if (!$order_goods_id) {

                    $this->error = '参数错误';

                    return false;

                }



                $orderGoods = Db::name('shop_refund_order_goods')->where('id',$order_goods_id)->find();

                if(!$orderGoods)

                {

                    $this->error = '订单商品不存在';

                    return false;

                }



                $orderCount = Db::name('shop_refund_order_goods')->where('order_id',$orderGoods['order_id'])->count();

                if($orderCount == 1)

                {

                    $this->error = '订单中至少保留一个有效商品';

                    return false;

                }



                $bool = Db::name('shop_refund_order_goods')->where(['id'=>$order_goods_id])->delete();

                if ($bool !== false) {

                    // 添加操作记录

                    $content = '将商品【' . $orderGoods['goods_name'] . '】删除';

                    $this->addActionRecord($request['operator_id'],'shop_refund_order_goods',$order_id,$content,'shop','order',json_encode($orderGoods));



                    $this->error = '删除订单商品成功';



                    $saveBool = true;

                }

            }



            if ($saveBool) {

                // 更新订单金额

                $payMount   = Db::name('shop_refund_order_goods')->where('order_id', '=', $order_id)->sum('pay_price*number');

                $updateData = [

                    'order_amount' => $payMount,

                    'pay_amount'   => $payMount,

                    'update_time'  => time()

                ];

                $this->where('id', '=', $order_id)->update($updateData);

                return true;

            }

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return false;

        }

        $this->error = '操作失败';

        return false;

    }



    /**

     * 修改订单状态

     * 审核、反审核、作废、确认收货

     * @param array $request 请求参数

     * @return bool

     * @author SL

     * @create 2021-06-08

     */

    public function checkOrderData($request)

    {
        // echo "<pre>";
        // print_r($request);
        // exit;

        $is_cancel = $request['is_cancel'] ?? 0;

        $id = $request['order_id'] ?? 0;

        $status = $request['status'] ?? 0;

        if (!$id) {

            $this->error = '参数错误';

            return false;

        }

        $content = '';

        $order = Db::name('shop_refund_order')->where('id',$id)->find();

        // echo "<pre>";
        // print_r($order);

        $deal_time = date('Y-m-d',$order['deal_time']);

        // echo $deal_time;
        // exit;

        if(!$order)

        {

            $this->error = '订单不存在';

            return false;

        }

        // 订单作废

        if($status !== 3)

        {

            $this->error = '订单状态不正确';

            return false;

        }


        if($is_cancel=='1'){
            // echo "申请退款";

            // echo "<pre>";
            // print_r($order);

            if($order['sales_organization'] == $order['settlement_organization']){
                $shop_id = $order['shop_id'];
            }else{
                $shop_id = $request['shop_id'];
            }

            $shop = Db::name('shop')->where('shop_id',$shop_id)->find();

            // echo "<pre>";
            // print_r($shop);
            // exit;

            $saveData = [];

            if($order['shanghu_type'] == '1'){ // 公户

                $saveData['private_key'] = $shop['shop_gonghu_privateKey']; // 密钥
                $saveData['cusid'] = $shop['shop_gonghu_cusid']; // 商户号
                $saveData['appid'] = $shop['shop_gonghu_appid']; // 商户appid

            }

            if($order['shanghu_type'] == '2'){ // 私户

                $saveData['private_key'] = $shop['shop_sihu_privateKey']; // 密钥
                $saveData['cusid'] = $shop['shop_sihu_cusid']; // 商户号
                $saveData['appid'] = $shop['shop_sihu_appid']; // 商户appid

            }

            $saveData['pay_amount'] = $order['pay_amount'];
            $saveData['reqsn'] = 'CX_'.$order['refund_order_no'];
            $saveData['refund_order_no'] = $order['refund_order_no'];

            $payModel = new RefundPayModel();

            $res = $payModel->cancel($saveData);

            // var_dump($res);

            if($res['retcode'] == 'FAIL'){

                $this->error = $res['retmsg'];

                return false;

            }
        }

        $turnModel = new TurnRefund();

        $mainTurn = Db::name('shop_refund_order_turn')->where([['main_refund_order_no','=',$order['refund_order_no'],['status','<>',3]]])->find();

        if($mainTurn){
            // echo "作废主单";
            // echo "<pre>";
            // print_r($mainTurn);

            $turnModel->deleteTurn('main',$order['refund_order_no']);
        }

        $viceTurn = Db::name('shop_refund_order_turn')->where([['vice_refund_order_no','=',$order['refund_order_no'],['status','<>',3]]])->find();

        if($viceTurn){
            // echo "作废从单";
            // echo "<pre>";
            // print_r($viceTurn);

            $turnModel->deleteTurn('vice',$order['refund_order_no']);

            $this->error = '操作成功!!!';
			return true;
        }

        // echo "<pre>";
        // print_r($mainTurn);
        // exit;
        // exit;

        try {

            $arr = [0=>'待退款',1=>'已退款',2=>'已下推',3=>'已作废'];

            $content .= '，状态：【' . $arr[$order['status']] . '】修改为【' . $arr[$status] . '】';

            $data['status'] = $status; // 订单状态： 订单状态：0.待支付 1.已支付 2.已下推 3.已评价 4.已取消

            $data['update_time'] = time();

            $bool = $this->where(['id'=>$id])->update($data);


			if($order['type']=='3'){
				//echo '收款单--进入';echo '<br/>';
				if(isset($order['is_pay'])){

					$is_pay = $order['is_pay'];
				}else{
					$is_pay = '3'; // 3代表以前录入的订单;
				}
			}else{
				//echo '不是---收款单--进入';echo '<br/>';
				$is_pay = '1';
			}
            //if($order['type']=='3'){
			// 订单已支付

			// 如果作废订单类型为收款单或者退款单时，需要调整顾客累计消费

			$customer_id   = $order['uid'];    // 客户的id
			$customer_info = Db::name('customer')->where('id',$customer_id)->find();

			$updateCustomer = [];
			if($order['type'] == '1' && $order['refund_type'] !== '101.03'){ // 作废退款单  退款调整不计算客户累计消费金额
				$consumption = $customer_info['consumption']; // 订单作废前顾客的累计消费
				$new_consumption = bcadd($consumption,$order['pay_amount'],2); //订单作废后顾客的累计消费

				$updateCustomer['consumption'] = $new_consumption;

			}

			if($order['type'] == '3' &&  $order['refund_type'] =='101.02' && $order['is_pay'] == '1'){ // 作废收款单
				$consumption = $customer_info['consumption']; // 订单作废前顾客的累计消费
				$new_consumption = bcsub($consumption,$order['pay_amount'],2); //订单作废后顾客的累计消费

				$updateCustomer['consumption'] = $new_consumption;

				// Db::name('customer')->where(['id'=>$id])->update($updateCustomer);

			}

			if($updateCustomer){
				Db::name('customer')->where(['id'=>$customer_id])->update($updateCustomer);
			}
			// exit;



			if ($bool !== false) {

				// 处理客户的余额 //

				$customerModel = new \app\crm\model\Customer();

				$customer_id   = $order['uid'];    // 客户的id

				$type = 2;
                //type  1退款单 2退货单 3收款单
				if($order['type'] == 1 ){
					$type = 1;
				}
				
				
				if($is_pay=='0'){
					$balanceData   = [];
				}else{

					// // 新增 青春痘 和皮肤
					// if( $order['business_type'] == 1 || $order['business_type'] == 3){
					// 	$business_type = 1;
					// }else{
					// 	$business_type = 2;
					// }

                    $business_type = $order['business_type'];

//					$balanceData   = [                // 余额变更数据集
//
//						'change_type'  => $type,      // 变动类型 1:增加 2:减少
//
//						'change_money' => $order['pay_amount'],      // 变更的本金
//
//						'complimentary_money' => $order['gift_amount'],  // 变更的赠金
//
//						'balance_category_id' => $business_type // 变更的余额的类型 1:疤痕 2:项目 3:青春痘 4:护肤品
//						//'balance_category_id' => $order['business_type'] // 变更的余额的类型 1:疤痕 2:项目
//
//					];

                    
                    $oneBalance  =  $onegiftBalance = $oneShopBalance  = [];
                    $twoBalance  =  $twogiftBalance = $twoShopBalance  = [];
                    $threeBalance = $threegiftBalance = $threeShopBalance  = [];
                    $fourBalance  = $fourgiftBalance = $fourShopBalance  = [];

                    if($order['type'] ==2 ){
                        
                        switch ($order['business_type']){
                                case  1:
                                    array_push($oneBalance,$order['pay_amount']);
                                    array_push($onegiftBalance,$order['gift_amount']);
                                    array_push($oneShopBalance,$order['shop_transfer_amount']);
                                    break;
                                case  2:
                                    array_push($twoBalance,$order['pay_amount']);
                                    array_push($twogiftBalance,$order['gift_amount']);
                                    array_push($twoShopBalance,$order['shop_transfer_amount']);
                                    break;
                                case  3:
                                    array_push($threeBalance,$order['pay_amount']);
                                    array_push($threegiftBalance,$order['gift_amount']);
                                    array_push($threeShopBalance,$order['shop_transfer_amount']);
                                    break;
                                case  4:
                                    array_push($fourBalance,$order['pay_amount']);
                                    array_push($fourgiftBalance,$order['pay_amount']);
                                    array_push($fourShopBalance,$order['shop_transfer_amount']);
                                    break;
                            }
                    }else{
                         $refundOrderGoods = DB::name('shop_refund_order_goods')->where('order_id',$order['id'])->select()->toArray();
                        foreach($refundOrderGoods as $key=>$v){
                            switch ($v['data_business_type']){
                                case  1:
                                    array_push($oneBalance,$v['pay_price']);
                                    array_push($onegiftBalance,$v['gift_price']);
                                    array_push($oneShopBalance,$v['shop_transfer_price']);
                                    break;
                                case  2:
                                    array_push($twoBalance,$v['pay_price']);
                                    array_push($twogiftBalance,$v['gift_price']);
                                    array_push($twoShopBalance,$v['shop_transfer_price']);
                                    break;
                                case  3:
                                    array_push($threeBalance,$v['pay_price']);
                                    array_push($threegiftBalance,$v['gift_price']);
                                    array_push($threeShopBalance,$v['shop_transfer_price']);
                                    break;
                                case  4:
                                    array_push($fourBalance,$v['pay_price']);
                                    array_push($fourgiftBalance,$v['gift_price']);
                                    array_push($fourShopBalance,$v['shop_transfer_price']);
                                    break;
                            }
                        }
                    }
                   
                    

                    $balanceData   = [                // 余额变更数据集

                        'change_type'  => $type,      // 变动类型 1:增加 2:减少

                        // 变更的余额的类型 1:疤痕 2:项目 3:青春痘 4:护肤品
                        'changeData' => [
                            ['balance_category_id'=>1,'change_money'=>array_sum($oneBalance),'complimentary_money'=>array_sum($onegiftBalance),'shop_transfer_money'=>array_sum($oneShopBalance)],
                            ['balance_category_id'=>2,'change_money'=>array_sum($twoBalance),'complimentary_money'=>array_sum($twogiftBalance),'shop_transfer_money'=>array_sum($twoShopBalance)],
                            ['balance_category_id'=>3,'change_money'=>array_sum($threeBalance),'complimentary_money'=>array_sum($threegiftBalance),'shop_transfer_money'=>array_sum($threeShopBalance)],
                            ['balance_category_id'=>4,'change_money'=>array_sum($fourBalance),'complimentary_money'=>array_sum($fourgiftBalance),'shop_transfer_money'=>array_sum($fourShopBalance)],
                        ],

                    ];
				}
			




				$newOrderData  = [   // 新单变更数据集

					// 'cj_time'  => ($data['type']==3 && $data['order_type']==1 && $total_amount>500)?$data['deal_time']:0,     // 成交时间-时间戳

					// 'cj_money'    => $total_amount,    // 成交金额

					'cj_order_id' => $id, // 成交的订单单号

					'cj_type' => 1, // 成交的订单单号

				];

				$orderInfo     = [       // 本次需要新增的订单金额

					// 'order_amount' => $pay_price, // 本次订单金额

					// 'order_time'   => $data['type']==3 ? $data['deal_time'] : 0,   // 本次订单的时间-时间戳

				];

				$member_products = 0; // 购买了几次会员商品

				$yhjOrderInfo  = [    // 本次需要处理的优惠卷

					'yhj_id '     => 0,      // 本次优惠卷的id

					'order_id  '  => 0,   // 本次订单的id

					'operator_id' => 0,  // 核销人的id

				];

				// echo "<pre>";
				// print_r($balanceData);
				// echo "</pre>";
				// exit;
				// echo "退款的订单时间为：".$deal_time;
				// echo "<br/>";
				$customerModel->processingFunds($customer_id,$balanceData,$deal_time,$newOrderData,$orderInfo,$yhjOrderInfo,$member_products);

				// exit;

				// 添加操作记录

				$this->addActionRecord($request['operator_id'], 'shop_refund_order_check', $id, $content, 'shop', 'refund');

                // 修改顾客最新消费时间
                $addLogModel = new AddOrderLog();

                $addLogModel->deletedData($customer_id,$order['refund_order_no']);

				$this->error = '操作成功';

				return true;

			}


            /* }else{
                // 收款单未支付
            } */



        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return false;

        }

        $this->error = '操作失败';

        return false;

    }



    /**

     * 订单设置发货

     * @param array $request 请求参数

     * @return bool

     * @author SL

     * @create 2021-06-08

     */

    public function sendOrderData($request)

    {

        $id = $request['order_id'] ?? 0;

        $king_send_no = $request['king_send_no'] ?? '';

        $king_sale_no = $request['king_sale_no'] ?? '';

        if (!$id || !$king_send_no || !$king_sale_no) {

            $this->error = '参数错误';

            return false;

        }



        $order = Db::name('shop_refund_order')->where('id',$id)->find();

        if(!$order)

        {

            $this->error = '订单不存在';

            return false;

        }



        if($order['status'] != 2)

        {

            $this->error = '订单当前状态不能设置发货';

            return false;

        }



        try {

            $time = time();

            $data = [

                'status'       => 3, // 订单状态：0.待审核 1.已审核,2.已下推,3.已发货,4.已收货,5已完成,6.已作废

                'king_send_no' => trim($request['king_send_no']),

                'king_sale_no'  => trim($request['king_sale_no']),

                'send_time' => $time,

                'update_time'  => $time, // 时间

            ];



            $bool = $this->where(['id'=>$id])->update($data);

            if ($bool !== false) {

                // 添加操作记录

                $logFieldArr = [

                    'king_send_no'    => '金蝶发货通知单号',

                    'king_sale_no'    => '金蝶销售出库单号',

                ];

                $logContentArr = [];

                foreach ($logFieldArr as $key => $val) {

                    if ($data[$key] != $order[$key]) {

                        $logContentArr[] = "'" . $val . "': " . $data[$key];

                    }

                }

                if ($logContentArr) {

                    $logContentStr = implode('.|.', $logContentArr);

                    $logContentStr = '设置发货成功。' . $logContentStr;

                    $this->addActionRecord($request['operator_id'], 'shop_refund_order_send', $id, $logContentStr, 'shop', 'order',json_encode($data));

                }



                $this->error = '设置发货成功';

                return true;

            }

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return false;

        }

        $this->error = '设置发货失败';

        return false;

    }





    /**

     * 生成订单号

     * @param  array $request 请求参数

     * @return String

     * @author SL

     * @create 2021-06-03

     */

    public function getOrderNo()

    {

        $order_sn = null;

        // 保证不会有重复订单号存在

        while(true){

            $order_sn = "TK".date('YmdHis').rand(1000,9999); // 订单编号

            $order_sn_count = DB::name('shop_refund_order')->where('refund_order_no', $order_sn)->count();

            if($order_sn_count == 0)

                break;

        }

        return $order_sn;

    }



    /**

     * 添加订单跟进

     * @param  array $request 请求参数

     * @return bool

     * @author SL

     * @create 2021-06-09 10:49

     */

    public function addFollow(array $request): bool

    {

        try {

            $orderId  = $request['order_id'] ?? 0;

            $contentType = $request['content_type'] ?? 0; // 1-联系客户 2-客户反馈 3-支付 4-客户确认 5-业务员确认 6-其他

            $is_confirm = $request['is_confirm'] ?? 0; // 是否确认 0-未确认 1-确认

            if (!$orderId || !$contentType) {

                $this->error = '参数错误';

                return false;

            }

            // 订单详情

            $orderInfo = Db::name('shop_refund_order')->field('status,is_pay')->where('id',$orderId)->find();

            if(($contentType == 3 && $is_confirm == 1 && in_array($orderInfo['status'], [5,6])) || $orderInfo['is_pay'])

            {

                $this->error = '订单当前状态不能添加支付跟进';

                return false;

            }



            $request['obj_id']      = $orderId;

            $request['follow_type'] = 4; // 1-线索 2-客户 3-商机 4-订单



            // 调用添加跟进

            $followModel = new FollowRecord();

            $bool        = $followModel->addData($request);

            if ($bool) {

                if($is_confirm == 1)

                {

                    if($contentType == 3)

                    {

                        $data = [

                            'is_pay' => 1, // 已支付

                            'pay_type' => 1, // 后台跟进,货到付款

                            'pay_time' => time()

                        ];

                        // 待审核

                        if($orderInfo['status'] == 0)

                        {

                            $data['status'] = 1;

                        }

                        // 已收货

                        if($orderInfo['status'] == 4)

                        {

                            $data['complete_time'] = time();

                        }



                    }

                    elseif($contentType == 4)

                    {

                        $data = [

                            'customer_confirm' => 1 // 客户已确认

                        ];

                    }

                    elseif($contentType == 5)

                    {

                        $data = [

                            'admin_user_confirm' => 1 // 客服(业务员)已确认

                        ];

                    }

                    else{



                    }

                    // 更新商机跟进时间

                    $data['update_time'] = time();

                    $this->where(['id' => $orderId])->update($data);

                }



                $this->error = '添加成功';

                return true;

            }



            $this->error = $followModel->getError();

        } catch (\Exception $e) {

            $this->error = '添加失败';

        }



        return false;

    }



    /**

     * 订单跟进列表

     * @param  array $request 请求参数

     * @return array

     * @author SL

     * @create 2021-06-09 11:21

     */

    public function getOrderFollowList(array $request): array

    {

        $orderId = $request['order_id'] ?? 0;

        if (!$orderId) {

            $this->error = '参数错误';

            return [];

        }



        $request['map'] = [

            ['field' => 'obj_id', 'value' => $orderId, 'type' => '='],

            ['field' => 'follow_type', 'value' => 4, 'type' => '=']

        ];

        $followModel = new FollowRecord();

        $data        = $followModel->getDataList($request);

        if (!$data) {

            $this->error = $followModel->getError();

            return [];

        }

        return $data;

    }



    /**

     * 订单操作记录

     * @param  array $request 请求参数

     * @return array

     * @author SL

     * @create 2021-06-10 9:33

     */

    public function getOrderRecordList(array $request): array

    {

        $orderId = $request['order_id'] ?? 0;

        if (!$orderId) {

            $this->error = '参数错误';

            return [];

        }



        $page  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;

        $limit = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;

        return $this->getActionRecordListByPage($orderId, 'shop', 'order', 0, $page, $limit);

    }



    /**

     * 选择客户

     * @param  array $request 请求参数

     * @return array

     * @author Mr.Liu Wuchen

     * @create 2021-08-05 13:57

     */

    public function getCustomerDataList(array $request): array

    {

        try {

            $userId = $request['user_id'] ?? 0;

            $name = isset($request['name']) && trim($request['name']) ? trim($request['name']) : '';

            $list = [];

            if ($name) {



                // 获取客户数据权限 的客户ID

                $dataAuthCustomerId = (new \app\crm\model\Customer())->getDataAuthCustomer($userId, 'order');



                $where = [

                    ['name', 'like', '%' . $name . '%']

                ];

                !in_array('all', $dataAuthCustomerId) && array_push($where, ['customer_id', 'in', $dataAuthCustomerId]);

                $field = ['customer_id', 'name'];

                $list = (new \app\crm\model\Customer())->getCustomerList($where, $field);

            }



            $this->error = '获取客户成功';

            $data['data'] = $list ?: [];

            return $data;

        } catch (\Exception $e) {

        }



        $this->error = '获取客户失败';

        return [];

    }



    /**

     * 锁定订单

     * @param  array $request 请求参数

     * @return array

     * @author LIU

     * @create 2021-10-26

     */

    public function lcokOrderData($request)

    {



        try {

            $userId  = $request['user_id'] ?? 0;

            $shopIds= $request['shopIds'] ?? '';

            $request = $this->fmtRequest($request);



            $map     = $request['map'] ?? [];

            $where   = [];

            if (!isset($map['type']))

            {

                $this->error = '请传入type类型';

                return [];

            }

            if (!in_array($map['type'],[1,2,3]))

            {

                $this->error = 'type类型不正确';

                return [];

            }



            $type      =$map['type']; // 订单类型 1退款单 2退货单 3收款单

            $uid      = isset($map['uid']) && $map['uid'] ? trim($map['uid']) : ''; // 会员id

            $shop_id      = isset($map['shop_id']) && $map['shop_id'] ? trim($map['shop_id']) : ''; // 门店id

            //$refund_order_no     = isset($map['refund_order_no']) && $map['refund_order_no'] ? trim($map['refund_order_no']) : ''; // 单号

            $consignee = isset($map['consignee']) && $map['consignee'] ? trim($map['consignee']) : ''; // 客户名称

            $start_time = isset($map['start_time']) && $map['start_time'] ? strtotime(date($map['start_time'])) : 0;

            $end_time = isset($map['end_time']) && $map['end_time'] ? strtotime(date($map['end_time'] . ' 23:59:59')) : 0;

            $shop_name = isset($map['shop_name']) && $map['shop_name'] ? trim($map['shop_name']) : ''; // 门店名称

            $business_type    = isset($map['business_type']) && intval($map['business_type']) ? intval($map['business_type']) : 0; // 订单状态

            $order_type       = isset($map['order_type']) && intval($map['order_type']) ? intval($map['order_type']) : 0; // 订单状态

            $low_total = isset($map['low_total']) && $map['low_total'] ? $map['low_total']: 0;//销售金额区间搜索最小值

            $large_total =  isset($map['large_total']) && $map['large_total'] ? $map['large_total']: 0;//销售金额区间搜索最大值

            // 获取客户数据权限 的客户名称

            if ($shopIds)

            {

                array_push($where, ['shop_id', 'in', $shopIds]);

            }

            if ($uid)

            {

                //门店id搜索

                array_push($where, ['uid', '=', $uid]);

            }

            if ($type)

            {

                //门店名称搜索

                array_push($where, ['type', '=', $type]);

            }

            if ($shop_id)

            {

                //门店名称搜索

                array_push($where, ['shop_id', '=', $shop_id]);

            }

            if ($consignee) {

                // 客户名称搜索

                array_push($where, ['consignee', 'like', '%'.$consignee.'%']);

            }



            if ($shop_name)

            {

                //门店名称搜索

                array_push($where, ['shop_name', 'like', '%'.$shop_name.'%']);

            }

            // 时间

            if($start_time && $end_time)

            {

                array_push($where, ['deal_time', 'between', "$start_time,$end_time"]);

            }



            if ($business_type)

            {

                //业务类型搜索

                array_push($where, ['business_type', '=', $business_type]);

            }

            if ($order_type)

            {

                //订单类型搜索

                array_push($where, ['order_type', '=', $order_type]);

            }

            //退货单以订单总额搜索

            if ($type==2)

            {

                if ($low_total && !$large_total)

                {

                    array_push($where, ['total_amount', 'egt', $low_total]);

                }

                if (!$low_total && $large_total)

                {

                    array_push($where, ['total_amount', 'elt', $large_total]);

                }

                if ($low_total && $large_total)

                {

                    array_push($where, ['total_amount', 'between', "$low_total,$large_total"]);

                }

            }else

            {

                //收款单 退款单以实际金额搜索

                if ($low_total && !$large_total)

                {

                    array_push($where, ['pay_amount', 'egt', $low_total]);

                }

                if (!$low_total && $large_total)

                {

                    array_push($where, ['pay_amount', 'elt', $large_total]);

                }

                if ($low_total && $large_total)

                {

                    array_push($where, ['pay_amount', 'between', "$low_total,$large_total"]);

                }

            }



            $sqlQuery = $this->where($where);

            $dataCount  = $sqlQuery->count();

            $bool=0;

            if ($dataCount) {

                $bool = $sqlQuery->update(['is_lock' => 1]);

            }

            $this->error = '锁定成功'.$bool.'单';

            $data              = [];

            $data['dataCount'] = $bool ?? 0;

            return $data;

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];

        }

    }


    /**

     * 未支付订单列表查询

     * @param  array $request 请求参数

     * @return array

     * @author LIU

     * @create 2021-10-26

     */
    public function getUnpaidList($request)
    {
        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";

        try {
            $userId  = $request['user_id'] ?? 0;

            $shopIds= $request['shopIds'] ?? '';

            $request = $this->fmtRequest($request);



            $map     = $request['map'] ?? [];

            $where   = [];

            if (!isset($map['type']))

            {

                $this->error = '请传入type类型';

                return [];

            }

            if (!in_array($map['type'],[1,2,3]))

            {

                $this->error = 'type类型不正确';

                return [];

            }



            $id = isset($map['id']) && $map['id'] ? $map['id'] : [];

            if ($id) {

                if (!is_array($id)) {

                    $id = [$id];

                }

                array_push($where, ['o.id', 'in', $id]);

            }

            array_push($where, ['o.status', '<>', 3]);//排除已作废的

            $type      =$map['type']; // 订单类型 1退款单 2退货单 3收款单

            $uid      = isset($map['uid']) && $map['uid'] ? trim($map['uid']) : ''; // 会员id

            $shop_id      = isset($map['shop_id']) && $map['shop_id'] ? trim($map['shop_id']) : ''; // 门店id

            //$refund_order_no     = isset($map['refund_order_no']) && $map['refund_order_no'] ? trim($map['refund_order_no']) : ''; // 单号

            $consignee = isset($map['consignee']) && $map['consignee'] ? trim($map['consignee']) : ''; // 客户名称

            $status       = isset($map['status']) && intval($map['status']) ? intval($map['status']) : 0; // 订单状态

            $start_time = isset($map['start_time']) && $map['start_time'] ? strtotime(date($map['start_time'])) : 0;

            $end_time = isset($map['end_time']) && $map['end_time'] ? strtotime(date($map['end_time'] . ' 23:59:59')) : 0;

            $shop_name = isset($map['shop_name']) && $map['shop_name'] ? trim($map['shop_name']) : ''; // 门店名称

            $business_type    = isset($map['business_type']) && intval($map['business_type']) ? intval($map['business_type']) : 0; // 订单状态

            $order_type       = isset($map['order_type']) && intval($map['order_type']) ? intval($map['order_type']) : 0; // 订单状态

            $low_total = isset($map['low_total']) && $map['low_total'] ? $map['low_total']: 0;//销售金额区间搜索最小值

            $large_total =  isset($map['large_total']) && $map['large_total'] ? $map['large_total']: 0;//销售金额区间搜索最大值

            $is_pay = $map['is_pay'] ?? ''; // 订单是否支付


            // 获取客户数据权限 的客户名称

            if ($shopIds)

            {

                array_push($where, ['o.shop_id', 'in', $shopIds]);

            }

            if ($uid)

            {

                //门店id搜索

                array_push($where, ['o.uid', '=', $uid]);

            }

            if ($type)

            {

                //门店名称搜索

                array_push($where, ['o.type', '=', $type]);

            }

            if ($shop_id)

            {

                //门店名称搜索

                array_push($where, ['o.shop_id', '=', $shop_id]);

            }

            if ($consignee) {

                // 客户名称搜索

                array_push($where, ['o.consignee', 'like', '%'.$consignee.'%']);

            }



            if ($shop_name)

            {

                //门店名称搜索

                array_push($where, ['o.shop_name', 'like', '%'.$shop_name.'%']);

            }

            if ($consignee) {

                // 客户搜索

                array_push($where, ['o.consignee', 'like', '%'.$consignee.'%']);

            }

            if ($status != -1) {

                array_push($where, ['o.status', '=', $status]);

            }

            if ($is_pay == '0') {

                array_push($where, ['o.is_pay', '=', $is_pay]);

            }


            // 时间

            if($start_time && $end_time)

            {

                array_push($where, ['o.deal_time', 'between', "$start_time,$end_time"]);

            }



            if ($business_type)

            {

                //业务类型搜索

                array_push($where, ['o.business_type', '=', $business_type]);

            }

            if ($order_type)

            {

                //订单类型搜索

                array_push($where, ['o.order_type', '=', $order_type]);

            }

            //退货单以订单总额搜索

            if ($type==2)

            {

                if ($low_total && !$large_total)

                {

                    array_push($where, ['o.total_amount', 'egt', $low_total]);

                }

                if (!$low_total && $large_total)

                {

                    array_push($where, ['o.total_amount', 'elt', $large_total]);

                }

                if ($low_total && $large_total)

                {

                    array_push($where, ['o.total_amount', 'between', "$low_total,$large_total"]);

                }

            }else

            {

                //收款单 退款单以实际金额搜索

                if ($low_total && !$large_total)

                {

                    array_push($where, ['o.pay_amount', 'egt', $low_total]);

                }

                if (!$low_total && $large_total)

                {

                    array_push($where, ['o.pay_amount', 'elt', $large_total]);

                }

                if ($low_total && $large_total)

                {

                    array_push($where, ['o.pay_amount', 'between', "$low_total,$large_total"]);

                }

            }



            $sqlQuery = $this->alias('o')

                ->where($where);

            $dataCount  = $sqlQuery->count();

            $sum_ben_amount=0;

            $sum_zeng_amount=0;

            $sum_amount  =0;

            // echo $dataCount;

            // echo "<pre>";
            // print_r($where);
            // echo "</pre>";

            // exit;

            if ($dataCount) {

                // 订单列表

                //退款单 收款单

                if (in_array($type,[1,3]))

                {

                    $sum_ben_amount  = $sqlQuery->sum('o.pay_amount');

                    $sum_zeng_amount  = $sqlQuery->sum('o.gift_amount');

                    $field = ['o.id','o.consignee', 'o.order_type','o.is_lock','o.business_type','o.shop_name','o.create_time','o.shop_id','o.deal_time','o.type','o.type','o.sale_name','c.king_no','o.pay_amount as pay_price','o.gift_amount as gift_price','o.refund_type','o.refund_type_plus','o.shop_transfer_amount as shop_transfer_price'];

                    $list = $sqlQuery->field($field)

                        ->join('customer c', 'o.uid = c.id')

                        // ->join('shop_refund_order_goods g', 'o.id = g.order_id')

                        ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])

                        ->order('id DESC')

                        ->select()->toArray();

                }

                if ($list) {
                    //,'g.refund_mode_name'

                    foreach($list as &$v){

                        $v['proceeds'] = bcadd($v['shop_transfer_price'],$v['pay_price'],2);

                        $v['order_type']=$v['order_type']==1?'新单':'补单';

                        $v['business_type']=$v['business_type']==1?'疤痕':'项目';

                        if($v['refund_type']=='101.01'){
                            $refund_type = '店面转诊';
                        }elseif ($v['refund_type']=='101.02') {
                            $refund_type = '退款';
                        }else {
                            $refund_type = '退款调整';
                        }

                        $v['refund_type']=$refund_type;

                        $v['deal_time']=date('Y-m-d', $v['deal_time']);

                        $where = [];

                        array_push($where,['order_id','=',$v['id']]);

                        $refund_goods = Db::name('shop_refund_order_goods')->where($where)->select()->toArray();

                        $v['refund_mode_name'] = $refund_goods[0]['refund_mode_name'];

                    }

                }

            }



            $permission = get_user_permission_menu($userId,'order_list_tag');



            $data              = [];

            $data['menu_list'] = $permission ? $permission : [];

            $data['list']      = $list ?? [];

            $data['dataCount'] = $dataCount ?? 0;

            if($start_time && $end_time) {

                if (in_array($type, [1, 3])) {

                    $data['sum_ben_amount'] = $sum_ben_amount ?? 0;

                    $data['sum_zeng_amount'] = $sum_zeng_amount ?? 0;

                } else {

                    $data['sum_amount'] = $sum_amount ?? 0;

                }

            }

            return $data;

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];

        }
    }


    /**
     * 客户数据分析表
     */
    public function getAnalysis2($request)
    {
        $start_time = strtotime($request['start_time']);
        $end_time = strtotime($request['end_time']);
        $type = $request['type']??"";
        $where = [];
        array_push($where,['date','>=',$start_time]);
        array_push($where,['date','<=',$end_time]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        if(!empty($type))
        {
            array_push($where,['b.type','=',$type]);
        }
        $data = Db::name('shop_customer_analyse')->alias('a')
            ->join('shop b','a.shop_id = b.shop_id','left')
            ->field('a.shop_id,sum(a.bh_store) as bh_store,sum(a.dd_store) as dd_store,sum(a.xm_store) as xm_store,sum(a.store_sum) as store_sum,sum(a.bh_receive) as bh_receive,sum(a.dd_receive) as dd_receive,sum(a.xm_receive) as xm_receive
            ,sum(a.receive_sum) as receive_sum,sum(a.bh_receive_deal) as bh_receive_deal,sum(a.dd_receive_deal) as dd_receive_deal,sum(a.xm_receive_deal
            ) as xm_receive_deal,sum(a.receive_deal_sum) as receive_deal_sum,sum(a.bh_receive_money) as bh_receive_money,sum(a.dd_receive_money) as dd_receive_money,sum(a.xm_receive_money) as xm_receive_money
            ,sum(a.receive_money_sum) as receive_money_sum,sum(a.bh_direct) as bh_direct,sum(a.dd_direct) as dd_direct,sum(a.xm_direct) as xm_direct,sum(a.direct_sum) as direct_sum
            ,sum(a.bh_direct_money) as bh_direct_money,sum(a.dd_direct_money) as dd_direct_money,sum(a.xm_direct_money) as xm_direct_money,sum(a.direct_money_sum) as direct_money_sum,b.shop_name,b.market_name,b.market_id')
            ->where($where)
            ->group('shop_id')
            ->order('b.market_name')
            ->select()->toArray();
        $totalData = Db::name('shop_customer_analyse')->alias('a')
            ->join('shop b','a.shop_id = b.shop_id','left')
            ->field('sum(a.bh_store) as bh_store,sum(a.dd_store) as dd_store,sum(a.xm_store) as xm_store,sum(a.store_sum) as store_sum,sum(a.bh_receive) as bh_receive,sum(a.dd_receive) as dd_receive,sum(a.xm_receive) as xm_receive
            ,sum(a.receive_sum) as receive_sum,sum(a.bh_receive_deal) as bh_receive_deal,sum(a.dd_receive_deal) as dd_receive_deal,sum(a.xm_receive_deal
            ) as xm_receive_deal,sum(a.receive_deal_sum) as receive_deal_sum,sum(a.bh_receive_money) as bh_receive_money,sum(a.dd_receive_money) as dd_receive_money,sum(a.xm_receive_money) as xm_receive_money
            ,sum(a.receive_money_sum) as receive_money_sum,sum(a.bh_direct) as bh_direct,sum(a.dd_direct) as dd_direct,sum(a.xm_direct) as xm_direct,sum(a.direct_sum) as direct_sum
            ,sum(a.bh_direct_money) as bh_direct_money,sum(a.dd_direct_money) as dd_direct_money,sum(a.xm_direct_money) as xm_direct_money,sum(a.direct_money_sum) as direct_money_sum')
            ->where($where)
            ->select()->toArray();
        if($totalData)
        {
            $totalData[0]['shop_id']=0;
            $totalData[0]['shop_name']="";
            $totalData[0]['market_name']="汇总";
            $totalData[0]['market_id']=9999;
            $data = array_merge($data,$totalData);
        }
        $result = [];
        foreach($data as $key =>$value)
        {
            $data[$key]['money_sum'] = $value['receive_money_sum']+$value['direct_money_sum'];
            if(empty($value['bh_store']))
            {
                $data[$key]['bh_rate'] = 0;
            }else{
                $data[$key]['bh_rate'] = ($value['bh_receive_deal']+$value['bh_direct'])/$value['bh_store'];
            }
            $data[$key]['bh_rate'] = round($data[$key]['bh_rate'],4)*100;
            $data[$key]['bh_rate'].="%";
            if(empty($value['dd_store']))
            {
                $data[$key]['dd_rate'] = 0;
            }else{
                $data[$key]['dd_rate'] = ($value['dd_receive_deal']+$value['dd_direct'])/$value['dd_store'];
            }
            $data[$key]['dd_rate'] = round($data[$key]['dd_rate'],4)*100;
            $data[$key]['dd_rate'].="%";
            if(empty($value['xm_store']))
            {
                $data[$key]['xm_rate'] = 0;
            }else{
                $data[$key]['xm_rate'] = ($value['xm_receive_deal']+$value['xm_direct'])/$value['xm_store'];
            }
            $data[$key]['xm_rate'] = round($data[$key]['xm_rate'],4)*100;
            $data[$key]['xm_rate'].="%";
            if(empty($request['export']))
            {
                if(empty($result[$value['market_id']]))
                {
                    $result[$value['market_id']]['market_name']=$value['market_name'];
                    $result[$value['market_id']]['list']=[];
                }
                array_push($result[$value['market_id']]['list'],$data[$key]);
            }else{
                array_push($result,$data[$key]);
            }
        }
        $result = array_merge($result,[]);
        return $result;
    }


	public function getAnalysis($request)
	{
	    $bh = [1, 2, 3, 4, 5, 6, 7, 8,655,656];
	    $dd = [10];
	    $xm = [9,11, 12];
	    $type = $request['type']??"";
	    $start_time = strtotime($request['start_time']);
	    $end_time = strtotime($request['end_time']);
	    $data = [];
	    $baseWhere = [];
	    $whereOr = [];
	    $whereType = [];
	    array_push($whereOr, ['a.first_time', 'between', [$start_time, $end_time]]);
	    array_push($whereOr, ['a.second_time', 'between', [$start_time, $end_time]]);
	    if (!empty($request['shopIds'])) {
	        array_push($baseWhere, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    if (!empty($type)) {
	        array_push($whereType, ['sh.type', '=', $type]);
	    } else {
	        array_push($whereType, ['sh.type', '>', 0]);
	    }
	    $where = array_merge($baseWhere, [['b.customer_setting_id_type', 'in', $bh]]);
	    //进店数量明细
	    //疤痕
	    $res = Db::name('customer')->alias('a')
	        ->join('customer_scar b', 'a.id = b.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->field('count(distinct a.id) as num,a.shop_id,sh.shop_name,sh.market_name,sh.market_id')
	        ->where($whereType)
	        ->where($where)
	        ->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })
	        ->group('a.shop_id')
	        ->order('sh.market_id')
	        ->select()->toArray();

	    foreach ($res as $value) {
	        $data[$value['shop_id']]['date'] = $start_time;
	        $data[$value['shop_id']]['shop_id'] = $value['shop_id'];
	        $data[$value['shop_id']]['bh_store'] = $value['num'];
	        $data[$value['shop_id']]['market_id'] = $value['market_id'];
	        $data[$value['shop_id']]['shop_name'] = $value['shop_name'];
	        $data[$value['shop_id']]['market_name'] = $value['market_name'];
	    }

	    //痘痘
	    $where = array_merge($baseWhere, [['b.customer_setting_id_type', 'in', $dd]]);
	    $res = Db::name('customer')->alias('a')
	        ->join('customer_scar b', 'a.id = b.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->field('count(a.id) as num,a.shop_id,sh.shop_name,sh.market_name,sh.market_id')
	        ->where($whereType)
	        ->where($where)
	        ->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })
	        ->group('a.shop_id')
	        ->order('sh.market_id')
	        ->select()->toArray();

	    foreach ($res as $value) {
	        $data[$value['shop_id']]['date'] = $start_time;
	        $data[$value['shop_id']]['shop_id'] = $value['shop_id'];
	        $data[$value['shop_id']]['dd_store'] = $value['num'];
	        $data[$value['shop_id']]['market_id'] = $value['market_id'];
	        $data[$value['shop_id']]['shop_name'] = $value['shop_name'];
	        $data[$value['shop_id']]['market_name'] = $value['market_name'];
	    }
	    //项目
	    $where = array_merge($baseWhere, [['b.customer_setting_id_type', 'in', $xm]]);
	    $res = Db::name('customer')->alias('a')
	        ->join('customer_scar b', 'a.id = b.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->field('count(a.id) as num,a.shop_id,sh.shop_name,sh.market_name,sh.market_id')
	        ->where($whereType)
	        ->where($where)
	        ->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })
	        ->group('a.shop_id')
	        ->order('sh.market_id')
	        ->select()->toArray();
	    foreach ($res as $value) {
	        $data[$value['shop_id']]['date'] = $start_time;
	        $data[$value['shop_id']]['shop_id'] = $value['shop_id'];
	        $data[$value['shop_id']]['xm_store'] = $value['num'];
	        $data[$value['shop_id']]['market_id'] = $value['market_id'];
	        $data[$value['shop_id']]['shop_name'] = $value['shop_name'];
	        $data[$value['shop_id']]['market_name'] = $value['market_name'];
	    }


	    //体验数量 疤痕
	    $where = [];
	    array_push($where, ['b.goods_id', '=', 168]);
	    array_push($where, ['c.customer_setting_id_type', 'in', $bh]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        ->join('customer_scar c', 'a.id = c.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,count(distinct(b.customer_id)) as num')->group('shop_id')->select()->toArray();

	    foreach ($res as $value) {
	        $data[$value['shop_id']]['bh_receive'] = $value['num'];
	    }

	    //体验数量 痘痘
	    $where = [];
	    array_push($where, ['b.goods_id', '=', 150]);
	    array_push($where, ['c.customer_setting_id_type', 'in', $dd]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        ->join('customer_scar c', 'a.id = c.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,count(distinct(b.customer_id)) as num')->group('shop_id')->select()->toArray();
	    foreach ($res as $value) {
	        $data[$value['shop_id']]['dd_receive'] = $value['num'];
	    }

	    //体验数量 项目
	    $where = [];
	    array_push($where, ['b.goods_id', '=', 165]);
	    array_push($where, ['c.customer_setting_id_type', 'in', $xm]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        ->join('customer_scar c', 'a.id = c.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,count(distinct(b.customer_id)) as num')->group('shop_id')->select()->toArray();
	    foreach ($res as $value) {
	        $data[$value['shop_id']]['xm_receive'] = $value['num'];
	    }

	    //体验成交数量
	    $where = [];
	    array_push($where, ['b.goods_id', '=', 168]);
	    array_push($where, ['a.cj_money', '>', 500]);
	    array_push($where, ['d.customer_setting_id_type', 'in', $bh]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        // ->join('shop_refund_order c','a.id = c.uid')
	        ->join('customer_scar d', 'a.id = d.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,count(distinct(a.id)) as num')->group('a.shop_id')->select()->toArray();
	    foreach ($res as $value) {
	        $data[$value['shop_id']]['bh_receive_deal'] = $value['num'];
	    }

	    $where = [];
	    array_push($where, ['b.goods_id', '=', 150]);
	    array_push($where, ['a.cj_money', '>', 500]);
	    array_push($where, ['d.customer_setting_id_type', 'in', $dd]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        // ->join('shop_refund_order c','a.id = c.uid')
	        ->join('customer_scar d', 'a.id = d.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,count(distinct(a.id)) as num')->group('a.shop_id')->select()->toArray();
	    foreach ($res as $value) {
	        $data[$value['shop_id']]['dd_receive_deal'] = $value['num'];
	    }

	    $where = [];
	    array_push($where, ['b.goods_id', '=', 165]);
	    array_push($where, ['a.cj_money', '>', 500]);
	    array_push($where, ['d.customer_setting_id_type', 'in', $xm]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        // ->join('shop_refund_order c','a.id = c.uid')
	        ->join('customer_scar d', 'a.id = d.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,count(distinct(a.id)) as num')->group('a.shop_id')->select()->toArray();
	    foreach ($res as $value) {
	        $data[$value['shop_id']]['xm_receive_deal'] = $value['num'];
	    }

	    //体验成交金额
	    $where = [];
	    array_push($where, ['b.goods_id', '=', 168]);
	    array_push($where, ['d.customer_setting_id_type', 'in', $bh]);
	    array_push($where, ['c.business_type', '=', 1]);
	    array_push($where, ['c.status', '=', 2]);
	    array_push($where, ['c.extra_type', '=', 0]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        ->join('shop_refund_order c', 'a.id = c.uid')
	        ->join('customer_scar d', 'a.id = d.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,sum(c.pay_amount) as num')->group('shop_id')->select()->toArray();

	    foreach ($res as $value) {
	        $data[$value['shop_id']]['bh_receive_money'] = $value['num'];
	    }
	    $where = [];
	    array_push($where, ['b.goods_id', '=', 150]);
	    array_push($where, ['d.customer_setting_id_type', 'in', $dd]);
	    array_push($where, ['c.business_type', '=', 1]);
	    array_push($where, ['c.status', '=', 2]);
	    array_push($where, ['c.extra_type', '=', 1]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        ->join('shop_refund_order c', 'a.id = c.uid')
	        ->join('customer_scar d', 'a.id = d.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,sum(c.pay_amount) as num')->group('shop_id')->select()->toArray();
	    foreach ($res as $value) {
	        $data[$value['shop_id']]['dd_receive_money'] = $value['num'];
	    }

	    $where = [];
	    array_push($where, ['b.goods_id', '=', 165]);
	    array_push($where, ['d.customer_setting_id_type', 'in', $xm]);
	    array_push($where, ['c.business_type', '=', 2]);
	    array_push($where, ['c.status', '=', 2]);
	    // array_push($where,['c.extra_type','=',0]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        ->join('shop_refund_order c', 'a.id = c.uid')
	        ->join('customer_scar d', 'a.id = d.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,sum(c.pay_amount) as num')->group('shop_id')->select()->toArray();
	    foreach ($res as $value) {
	        $data[$value['shop_id']]['xm_receive_money'] = $value['num'];
	    }

	    //直接成交人数
	    $where = [];
	    array_push($where, ['b.goods_id', 'not in', [168, 165, 150]]);
	    array_push($where, ['a.cj_money', '>', 500]);
	    array_push($where, ['d.customer_setting_id_type', 'in', $bh]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        // ->join('shop_refund_order c','a.id = c.uid')
	        ->join('customer_scar d', 'a.id = d.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,count(distinct(a.id)) as num')->group('a.shop_id')->select()->toArray();
	    foreach ($res as $value) {
	        $data[$value['shop_id']]['bh_direct'] = $value['num'];
	    }
	    $where = [];
	    array_push($where, ['b.goods_id', 'not in', [168, 165, 150]]);
	    array_push($where, ['a.cj_money', '>', 500]);
	    array_push($where, ['d.customer_setting_id_type', 'in', $dd]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        // ->join('shop_refund_order c','a.id = c.uid')
	        ->join('customer_scar d', 'a.id = d.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,count(distinct(a.id)) as num')->group('a.shop_id')->select()->toArray();
	    foreach ($res as $value) {
	        $data[$value['shop_id']]['dd_direct'] = $value['num'];
	    }
	    $where = [];
	    array_push($where, ['b.goods_id', 'not in', [168, 165, 150]]);
	    array_push($where, ['a.cj_money', '>', 500]);
	    array_push($where, ['d.customer_setting_id_type', 'in', $xm]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        // ->join('shop_refund_order c','a.id = c.uid')
	        ->join('customer_scar d', 'a.id = d.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,count(distinct(a.id)) as num')->group('a.shop_id')->select()->toArray();
	    foreach ($res as $value) {
	        $data[$value['shop_id']]['xm_direct'] = $value['num'];
	    }
	    //直接成交金额
	    $where = [];
	    array_push($where, ['b.goods_id', 'not in', [168, 165, 150]]);
	    array_push($where, ['d.customer_setting_id_type', 'in', $bh]);
	    array_push($where, ['c.business_type', '=', 1]);
	    array_push($where, ['c.status', '=', 2]);
	    array_push($where, ['c.extra_type', '=', 0]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        ->join('shop_refund_order c', 'a.id = c.uid')
	        ->join('customer_scar d', 'a.id = d.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,sum(c.pay_amount) as num')->group('shop_id')->select()->toArray();
	    foreach ($res as $value) {
	        $data[$value['shop_id']]['bh_direct_money'] = $value['num'];
	    }
	    $where = [];
	    array_push($where, ['b.goods_id', 'not in', [168, 165, 150]]);
	    array_push($where, ['d.customer_setting_id_type', 'in', $dd]);
	    array_push($where, ['c.business_type', '=', 1]);
	    array_push($where, ['c.status', '=', 2]);
	    array_push($where, ['c.extra_type', '=', 1]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        ->join('shop_refund_order c', 'a.id = c.uid')
	        ->join('customer_scar d', 'a.id = d.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,sum(c.pay_amount) as num')->group('shop_id')->select()->toArray();
	    foreach ($res as $value) {
	        $data[$value['shop_id']]['dd_direct_money'] = $value['num'];
	    }

	    $where = [];
	    array_push($where, ['b.goods_id', 'not in', [168, 165, 150]]);
	    array_push($where, ['d.customer_setting_id_type', 'in', $xm]);
	    array_push($where, ['c.business_type', '=', 2]);
	    array_push($where, ['c.status', '=', 2]);
	    array_push($where, ['c.extra_type', '=', 0]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        ->join('shop_refund_order c', 'a.id = c.uid')
	        ->join('customer_scar d', 'a.id = d.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,sum(c.pay_amount) as num')->group('shop_id')->select()->toArray();
	    foreach ($res as $value) {
	        $data[$value['shop_id']]['xm_direct_money'] = $value['num'];
	    }
	    $start_time = strtotime($request['start_time']);
	    $end_time = strtotime($request['end_time']);
	    $type = $request['type'] ?? "";
	    $totalWhere = [];
	    array_push($totalWhere, ['date', '>=', $start_time]);
	    array_push($totalWhere, ['date', '<=', $end_time]);
	    if (!empty($request['shopIds'])) {
	        array_push($totalWhere, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    if (!empty($type)) {
	        array_push($totalWhere, ['b.type', '=', $type]);
	    }
	    $totalData[0] = [
	        'bh_store' => 0,
	        'dd_store' => 0,
	        'xm_store' => 0,
	        'bh_receive' => 0,
	        'dd_receive' => 0,
	        'xm_receive' => 0,
	        'bh_receive_deal' => 0,
	        'dd_receive_deal' => 0,
	        'xm_receive_deal' => 0,
	        'receive_deal_sum' => 0,
	        'bh_receive_money' => 0,
	        'dd_receive_money' => 0,
	        'xm_receive_money' => 0,
	        'receive_money_sum' => 0,
	        'bh_direct' => 0,
	        'dd_direct' => 0,
	        'xm_direct' => 0,
	        'direct_sum' => 0,
	        'bh_direct_money' => 0,
	        'dd_direct_money' => 0,
	        'xm_direct_money' => 0,
	        'direct_money_sum' => 0,
	    ];
	    foreach ($data as $hz) {
	        if(array_key_exists('bh_store',$hz)){
	            $totalData[0]['bh_store'] += $hz['bh_store'];
	        }
	        if(array_key_exists('dd_store',$hz)){
	            $totalData[0]['dd_store'] += $hz['dd_store'];
	        }
	        if(array_key_exists('xm_store',$hz)){
	            $totalData[0]['xm_store'] += $hz['xm_store'];
	        }
	        if(array_key_exists('bh_receive',$hz)){
	            $totalData[0]['bh_receive'] += $hz['bh_receive'];
	        }
	        if(array_key_exists('dd_receive',$hz)){
	            $totalData[0]['dd_receive'] += $hz['dd_receive'];
	        }
	        if(array_key_exists('xm_receive',$hz)){
	            $totalData[0]['xm_receive'] += $hz['xm_receive'];
	        }
	        if(array_key_exists('bh_receive_deal',$hz)){
	            $totalData[0]['bh_receive_deal'] += $hz['bh_receive_deal'];
	        }
	        if(array_key_exists('dd_receive_deal',$hz)){
	            $totalData[0]['dd_receive_deal'] += $hz['dd_receive_deal'];
	        }
	        if(array_key_exists('xm_receive_deal',$hz)){
	            $totalData[0]['xm_receive_deal'] += $hz['xm_receive_deal'];
	        }
	        if(array_key_exists('receive_deal_sum',$hz)){
	            $totalData[0]['receive_deal_sum'] += $hz['receive_deal_sum'];
	        }
	        if(array_key_exists('bh_receive_money',$hz)){
	            $totalData[0]['bh_receive_money'] += $hz['bh_receive_money'];
	        }
	        if(array_key_exists('dd_receive_money',$hz)){
	            $totalData[0]['dd_receive_money'] += $hz['dd_receive_money'];
	        }
	        if(array_key_exists('xm_receive_money',$hz)){
	            $totalData[0]['xm_receive_money'] += $hz['xm_receive_money'];
	        }
	        if(array_key_exists('receive_money_sum',$hz)){
	            $totalData[0]['receive_money_sum'] += $hz['receive_money_sum'];
	        }
	        if(array_key_exists('bh_direct',$hz)){
	            $totalData[0]['bh_direct'] += $hz['bh_direct'];
	        }
	        if(array_key_exists('dd_direct',$hz)){
	            $totalData[0]['dd_direct'] += $hz['dd_direct'];
	        }
	        if(array_key_exists('xm_direct',$hz)){
	            $totalData[0]['xm_direct'] += $hz['xm_direct'];
	        }
	        if(array_key_exists('direct_sum',$hz)){
	            $totalData[0]['direct_sum'] += $hz['direct_sum'];
	        }
	        if(array_key_exists('bh_direct_money',$hz)){
	            $totalData[0]['bh_direct_money'] += $hz['bh_direct_money'];
	        }
	        if(array_key_exists('dd_direct_money',$hz)){
	            $totalData[0]['dd_direct_money'] += $hz['dd_direct_money'];
	        }
	        if(array_key_exists('xm_direct_money',$hz)){
	            $totalData[0]['xm_direct_money'] += $hz['xm_direct_money'];
	        }
	        if(array_key_exists('direct_money_sum',$hz)){
	            $totalData[0]['direct_money_sum'] += $hz['direct_money_sum'];
	        }
	    }
	    if ($totalData) {
	        $totalData[0]['shop_id'] = 0;
	        $totalData[0]['shop_name'] = "";
	        $totalData[0]['market_name'] = "汇总";
	        $totalData[0]['market_id'] = 9999;
	        $data = array_merge($data, $totalData);
	    }


	    foreach ($data as $key => $value) {
	        if (empty($value['bh_store'])) {
	            $data[$key]['bh_store'] = 0;
	        }
	        if (empty($value['dd_store'])) {
	            $data[$key]['dd_store'] = 0;
	        }
	        if (empty($value['xm_store'])) {
	            $data[$key]['xm_store'] = 0;
	        }
	        if (empty($value['bh_receive'])) {
	            $data[$key]['bh_receive'] = 0;
	        }
	        if (empty($value['dd_receive'])) {
	            $data[$key]['dd_receive'] = 0;
	        }
	        if (empty($value['xm_receive'])) {
	            $data[$key]['xm_receive'] = 0;
	        }
	        if (empty($value['bh_receive_deal'])) {
	            $data[$key]['bh_receive_deal'] = 0;
	        }
	        if (empty($value['dd_receive_deal'])) {
	            $data[$key]['dd_receive_deal'] = 0;
	        }
	        if (empty($value['xm_receive_deal'])) {
	            $data[$key]['xm_receive_deal'] = 0;
	        }
	        if (empty($value['bh_receive_money'])) {
	            $data[$key]['bh_receive_money'] = 0;
	        }
	        if (empty($value['dd_receive_money'])) {
	            $data[$key]['dd_receive_money'] = 0;
	        }
	        if (empty($value['xm_receive_money'])) {
	            $data[$key]['xm_receive_money'] = 0;
	        }
	        if (empty($value['bh_direct'])) {
	            $data[$key]['bh_direct'] = 0;
	        }
	        if (empty($value['dd_direct'])) {
	            $data[$key]['dd_direct'] = 0;
	        }
	        if (empty($value['xm_direct'])) {
	            $data[$key]['xm_direct'] = 0;
	        }
	        if (empty($value['bh_direct_money'])) {
	            $data[$key]['bh_direct_money'] = 0;
	        }
	        if (empty($value['dd_direct_money'])) {
	            $data[$key]['dd_direct_money'] = 0;
	        }
	        if (empty($value['xm_direct_money'])) {
	            $data[$key]['xm_direct_money'] = 0;
	        }
	        $data[$key]['store_sum'] = $data[$key]['bh_store'] + $data[$key]['dd_store'] + $data[$key]['xm_store'];
	        $data[$key]['receive_sum'] = $data[$key]['bh_receive'] + $data[$key]['dd_receive'] + $data[$key]['xm_receive'];
	        $data[$key]['receive_deal_sum'] = $data[$key]['bh_receive_deal'] + $data[$key]['dd_receive_deal'] + $data[$key]['xm_receive_deal'];
	        $data[$key]['receive_money_sum'] = $data[$key]['bh_receive_money'] + $data[$key]['dd_receive_money'] + $data[$key]['xm_receive_money'];
	        $data[$key]['bh_receive_money'] = round($data[$key]['bh_receive_money'],4);
	        $data[$key]['dd_receive_money'] = round($data[$key]['dd_receive_money'],4);
	        $data[$key]['xm_receive_money'] = round($data[$key]['xm_receive_money'],4);
	        $data[$key]['receive_money_sum'] = round($data[$key]['receive_money_sum'],4);
	        $data[$key]['direct_sum'] = $data[$key]['bh_direct'] + $data[$key]['dd_direct'] + $data[$key]['xm_direct'];
	        $data[$key]['direct_money_sum'] = $data[$key]['bh_direct_money'] + $data[$key]['dd_direct_money'] + $data[$key]['xm_direct_money'];
	        $data[$key]['direct_money_sum'] = round($data[$key]['direct_money_sum'],4);
	        $data[$key]['bh_direct_money'] = round($data[$key]['bh_direct_money'],4);
	        $data[$key]['dd_direct_money'] = round($data[$key]['dd_direct_money'],4);
	        $data[$key]['xm_direct_money'] = round($data[$key]['xm_direct_money'],4);

	        krsort($data[$key]);
	    }

	    $result = [];
	    foreach ($data as $key => $value) {
	        $data[$key]['money_sum'] = $value['receive_money_sum'] + $value['direct_money_sum'];
	        $data[$key]['money_sum'] = round($data[$key]['money_sum'],4);
	        if (empty($value['bh_store'])) {
	            $data[$key]['bh_rate'] = 0;
	        } else {
	            $data[$key]['bh_rate'] = ($value['bh_receive_deal'] + $value['bh_direct']) / $value['bh_store'];
	        }
	        $data[$key]['bh_rate'] = round($data[$key]['bh_rate'], 4) * 100;
	        $data[$key]['bh_rate'] .= "%";
	        if (empty($value['dd_store'])) {
	            $data[$key]['dd_rate'] = 0;
	        } else {
	            $data[$key]['dd_rate'] = ($value['dd_receive_deal'] + $value['dd_direct']) / $value['dd_store'];
	        }
	        $data[$key]['dd_rate'] = round($data[$key]['dd_rate'], 4) * 100;
	        $data[$key]['dd_rate'] .= "%";
	        if (empty($value['xm_store'])) {
	            $data[$key]['xm_rate'] = 0;
	        } else {
	            $data[$key]['xm_rate'] = ($value['xm_receive_deal'] + $value['xm_direct']) / $value['xm_store'];
	        }
	        $data[$key]['xm_rate'] = round($data[$key]['xm_rate'], 4) * 100;
	        $data[$key]['xm_rate'] .= "%";
	        if (empty($request['export'])) {
	            if (empty($result[$value['market_id']])) {
	                $result[$value['market_id']]['market_name'] = $value['market_name'];
	                $result[$value['market_id']]['list'] = [];
	            }
	            array_push($result[$value['market_id']]['list'], $data[$key]);
	        } else {
	            array_push($result, $data[$key]);
	        }
	    }
	    $result = array_merge($result, []);
	    return $result;
	}
}

